One of the primary issues that developers avoid is code repetition, especially when more that 3 instances exist. When developing I follow the guidelines best explained by:

If you do it more than 3 times, functionalise. If you do it more than 10 times, refactor.

My most recent project is built using the CodeIgniter (CI) framework which I was extremely impressed with. The level of abstraction and ability to extend makes CI a very appealing solution to any developer.

Validation routines in CI out of the box are pretty comprehensive allowing input to be manipulated and validated using routines to xss_filter, check email validity and many more found here.

In the absence of a routine to validate the data you require the Form_Validation class can be extended using a MY_Form_Validation class. The class must use the prefix of MY_ to notify the CI core classes that your extension must be called rather than the CI core Form_Validation class. The parent validation class must be called within the constructor by doing parent::Form_Validation and extending CI_Form_Validation in the class declaration.

An example class will look like this:


class MY_Form_Validation extends CI_Form_Validation
{
    function __construct()
    {
        parent::CI_Form_Validation();
    }
}

MY_Form_Validation then needs saving into system/application/libraries/.

Then we can start writing validation routines to use in form_validations set_rules function.

Below is an example of a validation routine to validate a UK post code. Please note the regex was supplied as a government standard regex for UK post codes.

function valid_postcode($pc) {
        $regex = '!^([A-PR-UWYZa-pr-uwyz]([0-9]{1,2}|([A-HK-Ya-hk-y][0-9]|[A-HK-  Ya-hk-y][0-9]([0-9]|[ABEHMNPRV-Yabehmnprv-y]))|[0-9][A-HJKS-UWa-hjks-uw])\ {0,1}[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}|([Gg][Ii][Rr]\ 0[Aa][Aa])|([Ss][Aa][Nn]\ {0,1}[Tt][Aa]1)|([Bb][Ff][Pp][Oo]\ {0,1}([Cc]\/[Oo]\ )?[0-9]{1,4})|(([Aa][Ss][Cc][Nn]|[Bb][Bb][Nn][Dd]|[BFSbfs][Ii][Qq][Qq]|[Pp][Cc][Rr][Nn]|[Ss][Tt][Hh][Ll]|[Tt][Dd][Cc][Uu]|[Tt][Kk][Cc][Aa])\ {0,1}1[Zz][Zz]))$!';

        $result = preg_match($regex, $pc);

        if($result > 0) {
            return TRUE;
        } else {
            $this->set_message('valid_postcode', 'Please enter a valid postcode');
            return FALSE;
        }
    }

And finally in order to use this just use the set_rules function as per the example below.

$this->form_validation->set_rules(
     'post_code',
     'Postcode',
     'required|valid_postcode'
);