@larissa
To validate a form in CodeIgniter, you can follow these steps:
- Loading the form validation library:
You first need to load the form validation library in your controller. You can do this by adding the following line of code in your controller's constructor or method:
1
|
$this->load->library('form_validation');
|
- Setting validation rules:
You can set validation rules for your form fields using the set_rules() method of the form validation library. You can define these rules in the controller method that processes the form submission. Here's an example of setting validation rules for a form field:
1
|
$this->form_validation->set_rules('username', 'Username', 'required');
|
In the example above, 'username' is the name of the form field, 'Username' is the label for the form field that will be used in error messages, and 'required' is the validation rule that specifies that the field is required.
- Running the validation:
After setting the validation rules, you can run the validation by calling the run() method of the form validation library. This method returns a boolean value indicating whether the form data passed the validation rules. Here's an example of running the validation:
1
2
3
4
5
6
7
|
if ($this->form_validation->run() == FALSE) {
// Form validation failed
// Handle errors
} else {
// Form validation passed
// Proceed with form submission
}
|
- Displaying validation errors:
If the form validation fails, you can display the validation errors using the validation_errors() function. You can display these errors in your view where the form is located. Here's an example of displaying validation errors:
1
|
echo validation_errors();
|
By following these steps, you can validate a form in CodeIgniter and display validation errors to the user when the form data does not meet the specified rules.