How to validate a single form field in codeigniter?

by haylee.mertz , in category: PHP Frameworks , 9 months ago

How to validate a single form field in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by jasen_gottlieb , 9 months ago

@haylee.mertz 

To validate a single form field in CodeIgniter, you can follow these steps:

  1. Load the Form Validation library in your controller file.
1
$this->load->library('form_validation');


  1. Set the validation rules for the specific form field using the set_rules method. For example, if you want to validate a field named username:
1
$this->form_validation->set_rules('username', 'Username', 'required');


In the above example, username is the name of the form field, Username is the field name that will be used in error messages, and required is the validation rule.

  1. Use the run method of the Form Validation library to perform the validation. This method returns a boolean value indicating whether the validation was successful or not. It automatically retrieves the input data based on the names of the form fields.
1
2
3
4
5
if ($this->form_validation->run()) {
    // Validation passed
} else {
    // Validation failed, handle the errors
}


  1. If the validation fails, you can display the error message using the form_error function.
1
echo form_error('username');


In the above example, 'username' is the name of the specific form field.


By following these steps, you can validate a single form field in CodeIgniter.