- This library has been deprecated. Use of the form_validation library is encouraged. -
- -Form Validation
- -Before explaining CodeIgniter's approach to data validation, let's describe the ideal scenario:
- --
-
- A form is displayed. -
- You fill it in and submit it. -
- If you submitted something invalid, or perhaps missed a required item, the form is redisplayed containing your data along with an error message describing the problem. -
- This process continues until you have submitted a valid form. -
On the receiving end, the script must:
- --
-
- Check for required data. -
- Verify that the data is of the correct type, and meets the correct criteria. (For example, if a username is submitted -it must be validated to contain only permitted characters. It must be of a minimum length, -and not exceed a maximum length. The username can't be someone else's existing username, or perhaps even a reserved word. Etc.) -
- Sanitize the data for security. -
- Pre-format the data if needed (Does the data need to be trimmed? HTML encoded? Etc.) -
- Prep the data for insertion in the database. -
Although there is nothing complex about the above process, it usually requires a significant -amount of code, and to display error messages, various control structures are usually placed within the form HTML. -Form validation, while simple to create, is generally very messy and tedious to implement.
- -CodeIgniter provides a comprehensive validation framework that truly minimizes the amount of code you'll write. -It also removes all control structures from your form HTML, permitting it to be clean and free of code. - -Overview
- -In order to implement CodeIgniter's form validation you'll need three things:
- --
-
- A View file containing the form. -
- A View file containing a "success" message to be displayed upon successful submission. -
- A controller function to receive and process the submitted data. -
Let's create those three things, using a member sign-up form as the example.
- -The Form
- -Using a text editor, create a form called myform.php. In it, place this code and save it to your applications/views/ -folder:
- - - - - -The Success Page
- - -Using a text editor, create a form called formsuccess.php. In it, place this code and save it to your applications/views/ -folder:
- - - - - -The Controller
- -Using a text editor, create a controller called form.php. In it, place this code and save it to your applications/controllers/ -folder:
- - - - - -Try it!
- -To try your form, visit your site using a URL similar to this one:
- -example.com/index.php/form/
-
-If you submit the form you should simply see the form reload. That's because you haven't set up any validation -rules yet, which we'll get to in a moment.
- - -Explanation
- -You'll notice several things about the above pages:
- -The form (myform.php) is a standard web form with a couple exceptions:
- --
-
- It uses a form helper to create the form opening. -Technically, this isn't necessary. You could create the form using standard HTML. However, the benefit of using the helper -is that it generates the action URL for you, based on the URL in your config file. This makes your application more portable -and flexible in the event your URLs change. - -
- At the top of the form you'll notice the following variable:
-
<?php echo $this->validation->error_string; ?>
- -This variable will display any error messages sent back by the validator. If there are no messages it returns nothing.
-
-
The controller (form.php) has one function: index(). This function initializes the validation class and -loads the form helper and URL helper used by your view files. It also runs -the validation routine. Based on -whether the validation was successful it either presents the form or the success page.
- -Since you haven't told the validation class to validate anything yet, it returns "false" (boolean false) by default. The run() -function only returns "true" if it has successfully applied your rules without any of them failing.
- - -Setting Validation Rules
- -CodeIgniter lets you set as many validation rules as you need for a given field, cascading them in order, and it even lets you prep and pre-process the field data -at the same time. Let's see it in action, we'll explain it afterwards.
- -In your controller (form.php), add this code just below the validation initialization function:
- -$rules['username'] = "required";
-$rules['password'] = "required";
-$rules['passconf'] = "required";
-$rules['email'] = "required";
-
-$this->validation->set_rules($rules);
-
-Your controller should now look like this:
- - - -Now submit the form with the fields blank and you should see the error message. -If you submit the form with all the fields populated you'll see your success page.
- -Note: The form fields are not yet being re-populated with the data when -there is an error. We'll get to that shortly, once we're through explaining the validation rules.
- - -Changing the Error Delimiters
- -By default, the system adds a paragraph tag (<p>) around each error message shown. You can easily change these delimiters with -this code, placed in your controller:
- -$this->validation->set_error_delimiters('<div class="error">', '</div>');
-
-In this example, we've switched to using div tags.
- -Cascading Rules
- -CodeIgniter lets you pipe multiple rules together. Let's try it. Change your rules array like this:
- - -$rules['username'] = "required|min_length[5]|max_length[12]";
-$rules['password'] = "required|matches[passconf]";
-$rules['passconf'] = "required";
-$rules['email'] = "required|valid_email";
-
-The above code requires that:
- --
-
- The username field be no shorter than 5 characters and no longer than 12. -
- The password field must match the password confirmation field. -
- The email field must contain a valid email address. -
Give it a try!
- -Note: There are numerous rules available which you can read about in the validation reference.
- - -Prepping Data
- -In addition to the validation functions like the ones we used above, you can also prep your data in various ways. -For example, you can set up rules like this:
- -$rules['username'] = "trim|required|min_length[5]|max_length[12]|xss_clean";
-$rules['password'] = "trim|required|matches[passconf]|md5";
-$rules['passconf'] = "trim|required";
-$rules['email'] = "trim|required|valid_email";
-
-In the above example, we are "trimming" the fields, converting the password to MD5, and running the username through -the "xss_clean" function, which removes malicious data.
- -Any native PHP function that accepts one parameter can be used as a rule, like htmlspecialchars, -trim, MD5, etc.
- -Note: You will generally want to use the prepping functions after -the validation rules so if there is an error, the original data will be shown in the form.
- -Callbacks: Your own Validation Functions
- -The validation system supports callbacks to your own validation functions. This permits you to extend the validation class -to meet your needs. For example, if you need to run a database query to see if the user is choosing a unique username, you can -create a callback function that does that. Let's create a simple example.
- -In your controller, change the "username" rule to this:
- -$rules['username'] = "callback_username_check";
-
-Then add a new function called username_check to your controller. Here's how your controller should look:
- - - - -Reload your form and submit it with the word "test" as the username. You can see that the form field data was passed to your -callback function for you to process.
- -To invoke a callback just put the function name in a rule, with "callback_" as the rule prefix.
- -The error message was set using the $this->validation->set_message function. -Just remember that the message key (the first parameter) must match your function name.
- -Note: You can apply your own custom error messages to any rule, just by setting the -message similarly. For example, to change the message for the "required" rule you will do this:
- -$this->validation->set_message('required', 'Your custom message here');
-
-Re-populating the form
- -Thus far we have only been dealing with errors. It's time to repopulate the form field with the submitted data. -This is done similarly to your rules. Add the following code to your controller, just below your rules:
- -$fields['username'] = 'Username';
-$fields['password'] = 'Password';
-$fields['passconf'] = 'Password Confirmation';
-$fields['email'] = 'Email Address';
-
-$this->validation->set_fields($fields);
-
-The array keys are the actual names of the form fields, the value represents the full name that you want shown in the -error message.
- -The index function of your controller should now look like this:
- - - - - -Now open your myform.php view file and update the value in each field so that it has an attribute corresponding to its name:
- - - - - -Now reload your page and submit the form so that it triggers an error. Your form fields should be populated -and the error messages will contain a more relevant field name.
- - - -Showing Errors Individually
- -If you prefer to show an error message next to each form field, rather than as a list, you can change your form so that it looks like this:
- - - - -If there are no errors, nothing will be shown. If there is an error, the message will appear, wrapped in the delimiters you -have set (<p> tags by default).
- -Note: To display errors this way you must remember to set your fields using the $this->validation->set_fields
-function described earlier. The errors will be turned into variables that have "_error" after your field name.
-For example, your "username" error will be available at:
$this->validation->username_error.
Rule Reference
- -The following is a list of all the native rules that are available to use:
- - - -Rule | -Parameter | -Description | -Example | -
---|---|---|---|
required | -No | -Returns FALSE if the form element is empty. | -- |
matches | -Yes | -Returns FALSE if the form element does not match the one in the parameter. | -matches[form_item] | -
min_length | -Yes | -Returns FALSE if the form element is shorter then the parameter value. | -min_length[6] | -
max_length | -Yes | -Returns FALSE if the form element is longer then the parameter value. | -max_length[12] | -
exact_length | -Yes | -Returns FALSE if the form element is not exactly the parameter value. | -exact_length[8] | -
alpha | -No | -Returns FALSE if the form element contains anything other than alphabetical characters. | -- |
alpha_numeric | -No | -Returns FALSE if the form element contains anything other than alpha-numeric characters. | -- |
alpha_dash | -No | -Returns FALSE if the form element contains anything other than alpha-numeric characters, underscores or dashes. | -- |
numeric | -No | -Returns FALSE if the form element contains anything other than numeric characters. | -- |
integer | -No | -Returns FALSE if the form element contains anything other than an integer. | -- |
valid_email | -No | -Returns FALSE if the form element does not contain a valid email address. | -- |
valid_emails | -No | -Returns FALSE if any value provided in a comma separated list is not a valid email. | -- |
valid_ip | -No | -Returns FALSE if the supplied IP is not valid. | -- |
valid_base64 | -No | -Returns FALSE if the supplied string contains anything other than valid Base64 characters. | -- |
Note: These rules can also be called as discrete functions. For example:
- -$this->validation->required($string);
-
-Note: You can also use any native PHP functions that permit one parameter.
- - - -Prepping Reference
- -The following is a list of all the prepping functions that are available to use:
- - - -Name | -Parameter | -Description | -
---|---|---|
xss_clean | -No | -Runs the data through the XSS filtering function, described in the Input Class page. | -
prep_for_form | -No | -Converts special characters so that HTML data can be shown in a form field without breaking it. | -
prep_url | -No | -Adds "http://" to URLs if missing. | -
strip_image_tags | -No | -Strips the HTML from image tags leaving the raw URL. | -
encode_php_tags | -No | -Converts PHP tags to entities. | -
Note: You can also use any native PHP functions that permit one parameter, -like trim, htmlspecialchars, urldecode, etc.
- - -Setting Custom Error Messages
- -All of the native error messages are located in the following language file: language/english/validation_lang.php
- -To set your own custom message you can either edit that file, or use the following function:
- -$this->validation->set_message('rule', 'Error Message');
-
-Where rule corresponds to the name of a particular rule, and Error Message is the text you would like displayed.
- - -Dealing with Select Menus, Radio Buttons, and Checkboxes
- -If you use select menus, radio buttons or checkboxes, you will want the state of -these items to be retained in the event of an error. The Validation class has three functions that help you do this:
- -set_select()
- -Permits you to display the menu item that was selected. The first parameter -must contain the name of the select menu, the second parameter must contain the value of -each item. Example:
- -
-<select name="myselect">
-<option value="one" <?php echo $this->validation->set_select('myselect', 'one'); ?> >One</option>
-<option value="two" <?php echo $this->validation->set_select('myselect', 'two'); ?> >Two</option>
-<option value="three" <?php echo $this->validation->set_select('myselect', 'three'); ?> >Three</option>
-</select>
-
-
-
-set_checkbox()
- -Permits you to display a checkbox in the state it was submitted. The first parameter -must contain the name of the checkbox, the second parameter must contain its value. Example:
- -<input type="checkbox" name="mycheck" value="1" <?php echo $this->validation->set_checkbox('mycheck', '1'); ?> />
-
-
-set_radio()
- -Permits you to display radio buttons in the state they were submitted. The first parameter -must contain the name of the radio button, the second parameter must contain its value. Example:
- -<input type="radio" name="myradio" value="1" <?php echo $this->validation->set_radio('myradio', '1'); ?> />
-
-
-
-
-
-