Form Validation

Codingox provides a comprehensive form validation and data prepping class that helps minimize the amount of code you’ll write.

Form Validation Tutorial

What follows is a “hands on” tutorial for implementing Codingox’s Form Validation.

In order to implement form validation you’ll need three things:

  1. A View file containing a form.
  2. A View file containing a “success” message to be displayed upon successful submission.
  3. A controller method 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 views/ folder:

<html>
<head>
<title>My Form</title>
</head>
<body>

<?php echo $this->form->form_error(); ?>

<?php echo form_open('form'); ?>

<h5>Username</h5>
<input type="text" name="username" value="" size="50" />

<h5>Password</h5>
<input type="text" name="password" value="" size="50" />

<h5>Password Confirm</h5>
<input type="text" name="passconf" value="" size="50" />

<h5>Email Address</h5>
<input type="text" name="email" value="" size="50" />

<div><input type="submit" value="Submit" /></div>

</form>

</body>
</html>

The Success Page

Using a text editor, create a form called formsuccess.php. In it, place this code and save it to your views/ folder:

<html>
<head>
<title>My Form</title>
</head>
<body>

<h3>Your form was successfully submitted!</h3>

<p><?php echo a_href('form', 'Try it again!'); ?></p>

</body>
</html>

The Controller

Using a text editor, create a controller called Form.php. In it, place this code and save it to your controllers/ folder:

<?php

class Form extends Base_Controller {

        public function index()
        {
                $this->helper(array('form', 'url'));

                $this->library('form');

                if ($this->form->is_valid() == FALSE)
                {
                        $this->view('myform');
                }
                else
                {
                        $this->view('formsuccess');
                }
        }
}

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.

Since you haven’t told the Form Validation class to validate anything yet, it returns FALSE (boolean false) by default.

Explanation

You’ll notice several things about the above pages:

The form (myform.php) is a standard web form with a couple exceptions:

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

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

    <?php echo $this->form->form_error(); ?>

    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.

Setting Validation Rules

Codingox 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 validate() method:

$this->form->validate();

The above method takes two parameters as input:

  1. The field name - the exact name you’ve given the form field.
  2. The validation rules for this form field.

Here is an example. In your controller (Form.php), add this code just below the validation initialization method:

$this->form->validate('username', 'required');
$this->form->validate('password', 'required');
$this->form->validate('email', 'required');

Your controller should now look like this:

<?php

class Form extends Base_Controller {

        public function index()
        {
                $this->helper(array('form', 'url'));

                $this->library('form');

                $this->form->validate('username', 'required');
                $this->form->validate('password', 'required');
                $this->form->validate('email', 'required');

                if ($this->form->is_valid() == FALSE)
                {
                        $this->view('myform');
                }
                else
                {
                        $this->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.

Setting Rules Using an Array

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(
    'username' => 'required',
    'password' => 'required|min_length[5]',
    'email'    => 'required|min_length[10]'
);

$this->form->validate($config);

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.  
min_length Yes Returns FALSE if the form element is shorter than the parameter value. min_length[3]
max_length Yes Returns FALSE if the form element is longer than the parameter value. max_length[12]
length Yes Returns FALSE if the form element is not exactly the parameter value. length[8]
greater_than Yes Returns FALSE if the form element is less than or equal to the parameter value or not numeric. greater_than[8]
less_than Yes Returns FALSE if the form element is greater than or equal to the parameter value or not numeric. less_than[8]
valid_url No Returns FALSE if the form element does not contain a valid URL.  
valid_text No Returns FALSE if the form element does not contain a valid text format.  
valid_email No Returns FALSE if the form element does not contain a valid email address.  
valid_number No Returns FALSE if the form element does not contain a valid number format.  

Class Reference

class form
validate($field, $rules = '')
Parameters:
  • $field (string) – Field name
  • $rules (mixed) – Validation rules, as a string list separated by a pipe “|”, or as an array or rules
Return type:

bool

Permits you to set validation rules, as described in the tutorial sections above:

is_valid()
Returns:

TRUE on success, FALSE if validation failed

Return type:

bool

form_error()
Returns:

Error message string

Return type:

string

Returns the error message for a specific field.