8 min read

Form validation is an important part of any application. Take a look at your favorite web application, notice that there are many forms in these web apps, and it is important that they be secure. It is also important that you have rules that should be adhered to; this also helps to keep a layer of security.

In this article by Adam Griffiths, author of CodeIgniter 1.7 Professional Development, you will:

  • Learn how the form validation process works
  • Build a contact form
  • Apply validation rules to the form’s input fields
  • Use callbacks to create your own rules

We will cover database interaction seperately.

(Read more interesting articles on CodeIgniter 1.7 Professional Development here.)

Why should I validate my forms?

The answer to this question is simple: security. If you simply left your forms bare, with no validation, and then stored this information directly in a database, you are liable to attack. People can simply place in some SQL code and can see a dump of a part or all of your database.

By using form validation and creating rules, you will disallow most, if not all, of these practices from occurring. By having set validation rules you can limit the types of data being allowed in your forms. Best of all, the Form Validation Library makes it easy to re-populate your form fields and to show individual errors for each field, making the overall end user experience better; which can mean a lot in an environment with many forms.

Even if you are building a contact form, it is a good idea to validate your forms to stop people abusing your form.

Using the Form Validation Library

In this article, we’ll go over a Contact Form and how to use the Form Validation Library methods for validation.

The form validation process

The Form Validation processes are different for the developers and for users. Read on to see how the user interacts with the forms, as well as how the developer will create the forms.

The user’s process

A form is displayed to the user, who then fills it in and submits it. The Form Validation Library then checks the form against any rules that the developer has set. If an error occurs the library returns these errors and they are shown against the form with the fields re-populated. This process proceeds until a valid form is submitted.

The development process

You create a form, along with a dynamic value from a form helper function—this will re-populate the data if needed. You will also display individual or global errors in the form view file. You set validation rules, which must be adhered to. Then you check to see if the validation process has been run, and if it has not, you load the form view file.

Contact form

We validate the form data using the Form Validation Library to complete tasks such as checking for empty fields, validating the e-mail, and then send the e-mail off. All of the code shown should be in the index() function of your email controller.

Loading the assets

We need to load two libraries for our contact form: the Form Validation Library and the Email class. We can do this in one line, by passing an array to the load->library function.

$this->load->library(array(’email’, ‘form_validation’));

We also need to load two helpers: the email helper and the form helper. We will do this in the same way as we loaded the two libraries in the previous line of code.

$this->load->helper(array(’email’, ‘form’));

Setting the rules

The next step in using the Form Validation Library is to set the rules for the form. These rules are set and must be adhered to. The way we set rules is by using the set_rules() function of the Form Validation Library. We use the function as follows:

$this->form_validation->
set_rules(‘field_name’, ‘human_name’, ‘rules’);

As you can see, the function accepts three parameters. The first is the name of the form field that you wish to set the rule for. The second parameter is the name that you wish to be assigned to this, for humans to read. The final parameter is where you pass any validation rules.

List of validation rules

The following rules are readily available for use:

  • required
  • matches[field_name]
  • min_length[x]
  • max_length[x]
  • exact_length[x]
  • alpha
  • alpha_numeric
  • alpha_dash
  • numeric
  • integer
  • is_natural
  • is_natural_no_zero
  • valid_email
  • valid_emails
  • valid_ip
  • valid_base64

As you can see, some of these rules have a single parameter.

The rule matches[] will return TRUE if the field matches the field name passed to it.

The min_length[], max_length[], and exact_length[] rules will take an integer as a parameter and check if the minimum length, maximum length respectively, or exact length matches the rule.

The rules with no parameters are pretty much self-explanatory. You are able to use more than one rule, simply separate rules with a vertical bar ‘|’ and they will cascade.

These rules can also be called as discrete functions. You may also use any native PHP function that accepts one parameter as a rule.

$this->form_validation->required($string);
$this->form_validation->is_array($string); // native PHP
// function as a rule

Prepping data

We can also use various prepping functions to prep the data before we apply rules to it. Here’s a list of the prepping rules that we can perform:

  • xss_clean
  • prep_for_form
  • prep_url
  • strip_image_tags
  • encode_php_tags

The first function listed is xss_clean. This basically strips out any code and unwanted characters, and replaces them with HTML entities.

The function prep_for_form will convert special characters so that HTML data can be shown in a form without breaking it.

The function prep_url will simply add http:// to a URL, if it is missing.

The function strip_image_tags will remove image tags, leaving the RAW image URL.

The function encode_php_tags will convert PHP tags into entities.

You may also use any native PHP function that accepts one parameter as a rule.

The rules

Now that we know how to set rules and what the rules we can use are, we can go ahead and set the rules necessary for our form. All fields should be required, and the e-mail field should be validated to ensure that the e-mail address is correctly formatted. We also want to run all of the data through the XSS filter.

$this->form_validation->
set_rules(‘name’, ‘Name’, ‘required|xss_clean’);
$this->form_validation->
set_rules(’email’, ‘Email Address’,
‘required|valid_email|xss_clean’);
$this->form_validation->
set_rules(‘subject’, ‘Subject’, ‘required|xss_clean’);
$this->form_validation->
set_rules(‘message’, ‘Message’, ‘required|xss_clean’);

Check the validation process

Instead of checking one of the form field’s POST value to check if the form has been submitted, we simply check to see if the Form Validation Library has run. We do this by using the following code:

if($this->form_validation->run() === FALSE)
{
// load the contact form
}
else

// send the email
}

It’s fairly simple: if the Form Validation Library hasn’t processed a form, we display the form to the user; if the library has processed a form and there are no errors, we’ll send the e-mail off.

Sending the email

As you’ll notice, everything is the same as how we got the field data earlier.

$name = $this->input->post(‘name’);
$email = $this->input->post(’email’);
$subject = $this->input->post(‘subject’);
$message = $this->input->post(‘message’);

$this->email->from($email, $name);
$this->email->to(‘[email protected]’);

$this->email->subject($subject);
$this->email->message($message);

$this->email->send();

Final controller code

Here is the entirety of our controller code:

<?php
class Email extends Controller
{
function Email()
{
parent::Controller();
} // function Email()
function index()
{
$this->load->library(array(’email’, ‘form_validation’));
$this->load->helper(array(’email’, ‘form’));
$this->form_validation->
set_rules(‘name’, ‘Name’, ‘required|xss_clean’);
$this->form_validation->
set_rules(’email’, ‘Email Address’,
‘required|valid_email|xss_clean’);
$this->form_validation->
set_rules(‘subject’, ‘Subject’, ‘required|xss_clean’);
$this->form_validation->
set_rules(‘message’, ‘Message’, ‘required|xss_clean’);
if($this->form_validation->run() == FALSE)
{
$this->load->view(’email’); // load the contact form
}
else
{
$name = $this->input->post(‘name’);
$email = $this->input->post(’email’);
$subject = $this->input->post(‘subject’);
$message = $this->input->post(‘message’);
$this->email->from($email, $name);
$this->email->to(‘[email protected]’);
$this->email->subject($subject);
$this->email->message($message);
$this->email->send();
}
} // function index()
} // class Email extends Controller
?>

LEAVE A REPLY

Please enter your comment!
Please enter your name here