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 terribly 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.

If you submit the form you should simply see the form reload. That’s
because you haven’t set up any validation rules yet.

Since you haven’t told the Form Validation class to validate anything
yet, it returns FALSE (boolean false) by default. ``The run()`` method
only returns TRUE if it has successfully applied your rules without any
of them failing.

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 in the event your URLs change.

At the top of the form you’ll notice the following function call:

<?phpechovalidation_errors();?>

This function will return any error messages sent back by the
validator. If there are no messages it returns an empty string.

The controller (Form.php) has one method: index(). This method
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.

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. To set validation rules you
will use the set_rules() method:

$this->form_validation->set_rules();

The above method takes three parameters as input:

The field name - the exact name you’ve given the form field.

A “human” name for this field, which will be inserted into the error
message. For example, if your field is named “user” you might give it
a human name of “Username”.

The validation rules for this form field.

(optional) Set custom error messages on any rules given for current field. If not provided will use the default one.

<?phpclassFormextendsCI_Controller{publicfunctionindex(){$this->load->helper(array('form','url'));$this->load->library('form_validation');$this->form_validation->set_rules('username','Username','required');$this->form_validation->set_rules('password','Password','required',array('required'=>'You must provide a %s.'));$this->form_validation->set_rules('passconf','Password Confirmation','required');$this->form_validation->set_rules('email','Email','required');if($this->form_validation->run()==FALSE){$this->load->view('myform');}else{$this->load->view('formsuccess');}}}

Now submit the form with the fields blank and you should see the error
messages. 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.

Before moving on it should be noted that the rule setting method can
be passed an array if you prefer to set all your rules in one action. If
you use this approach, you must name your array keys as indicated:

$config=array(array('field'=>'username','label'=>'Username','rules'=>'required'),array('field'=>'password','label'=>'Password','rules'=>'required','errors'=>array('required'=>'You must provide a %s.',),),array('field'=>'passconf','label'=>'Password Confirmation','rules'=>'required'),array('field'=>'email','label'=>'Email','rules'=>'required'));$this->form_validation->set_rules($config);

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! Submit your form without the proper data and you’ll see
new error messages that correspond to your new rules. There are numerous
rules available which you can read about in the validation reference.

Note

You can also pass an array of rules to set_rules(),
instead of a string. Example:

Thus far we have only been dealing with errors. It’s time to repopulate
the form field with the submitted data. CodeIgniter offers several
helper functions that permit you to do this. The one you will use most
commonly is:

set_value('field name')

Open your myform.php view file and update the value in each field
using the set_value() function:

Don’t forget to include each field name in the :php:func:`set_value()`
function calls!

The validation system supports callbacks to your own validation
methods. 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 method
that does that. Let’s create an example of this.

Then add a new method called username_check() to your controller.
Here’s how your controller should now look:

<?phpclassFormextendsCI_Controller{publicfunctionindex(){$this->load->helper(array('form','url'));$this->load->library('form_validation');$this->form_validation->set_rules('username','Username','callback_username_check');$this->form_validation->set_rules('password','Password','required');$this->form_validation->set_rules('passconf','Password Confirmation','required');$this->form_validation->set_rules('email','Email','required|is_unique[users.email]');if($this->form_validation->run()==FALSE){$this->load->view('myform');}else{$this->load->view('formsuccess');}}publicfunctionusername_check($str){if($str=='test'){$this->form_validation->set_message('username_check','The {field} field can not be the word "test"');returnFALSE;}else{returnTRUE;}}}

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 method
for you to process.

To invoke a callback just put the method name in a rule, with
“callback_” as the rule prefix. If you need to receive an extra
parameter in your callback method, just add it normally after the
method name between square brackets, as in: callback_foo[bar],
then it will be passed as the second argument of your callback method.

Note

You can also process the form data that is passed to your
callback and return it. If your callback returns anything other than a
boolean TRUE/FALSE it is assumed that the data is your newly processed
form data.

If callback rules aren’t good enough for you (for example, because they are
limited to your controller), don’t get disappointed, there’s one more way
to create custom rules: anything that is_callable() would return TRUE for.

The above code would use the valid_username() method from your
Users_model object.

This is just an example of course, and callbacks aren’t limited to models.
You can use any object/method that accepts the field value as its’ first
parameter. Or if you’re running PHP 5.3+, you can also use an anonymous
function:

Of course, since a Callable rule by itself is not a string, it isn’t
a rule name either. That is a problem when you want to set error messages
for them. In order to get around that problem, you can put such rules as
the second element of an array, with the first one being the rule name:

All of the native error messages are located in the following language
file: system/language/english/form_validation_lang.php

To set your own global custom message for a rule, you can either
extend/override the language file by creating your own in
application/language/english/form_validation_lang.php (read more
about this in the Language Class documentation),
or use the following method:

$this->form_validation->set_message('rule','Error Message');

If you need to set a custom error message for a particular field on
some particular rule, use the set_rules() method:

$this->form_validation->set_rules('field_name','Field Label','rule1|rule2|rule3',array('rule2'=>'Error Message on rule2 for this field_name'));

Where rule corresponds to the name of a particular rule, and Error
Message is the text you would like displayed.

If you’d like to include a field’s “human” name, or the optional
parameter some rules allow for (such as max_length), you can add the
{field} and {param} tags to your message, respectively:

$this->form_validation->set_message('min_length','{field} must have at least {param} characters.');

On a field with the human name Username and a rule of min_length[5], an
error would display: “Username must have at least 5 characters.”

Note

The old sprintf() method of using %s in your error messages
will still work, however it will override the tags above. You should
use one or the other.

In the callback rule example above, the error message was set by passing
the name of the method (without the “callback_” prefix):

By default, the Form Validation class adds a paragraph tag (<p>) around
each error message shown. You can either change these delimiters
globally, individually, or change the defaults in a config file.

Changing delimiters Globally
To globally change the error delimiters, in your controller method,
just after loading the Form Validation class, add this:

A nice feature of the Form Validation class is that it permits you to
store all your validation rules for your entire application in a config
file. You can organize these rules into “groups”. These groups can
either be loaded automatically when a matching controller/method is
called, or you can manually call each set as needed.

To store your validation rules, simply create a file named
form_validation.php in your application/config/ folder. In that file
you will place an array named $config with your rules. As shown earlier,
the validation array will have this prototype:

In order to organize your rules into “sets” requires that you place them
into “sub arrays”. Consider the following example, showing two sets of
rules. We’ve arbitrarily called these two rules “signup” and “email”.
You can name your rules anything you want:

An alternate (and more automatic) method of calling a rule group is to
name it according to the controller class/method you intend to use it
with. For example, let’s say you have a controller named Member and a
method named signup. Here’s what your class might look like: