Adding alpha_numeric_space to the Codeigniter Validation Library

Codeigniter Framework

Codeigniter Framework

I love Codeigniter, it is my favourite PHP framework by far!

The new form validation library I found was missing one handy validation function, whilst it has checks for alpha, alpha_numeric, alpha_dash and many other usefule ones, it was missing one that would proven to be very useful.

The alpha_numeric_space or you can also call it alpha_space, where all alpha numeric characters are accepted, but with the addition of accepting the space character as well. The code is terribly simple, but I thought I would share it just incase someone finds it useful!

The way I did it is to extend the Form_validation library, so everytime you load the Form_validation library, this file would also get loaded.

Name the file MY_Form_validation.php, or whatever your extension prefix would be (default is MY_). The prefix can be found and changed in the config.php file.

This is the code to put in the MY_Form_validation.php:

<?php
class MY_Form_validation extends CI_Form_validation {
function alpha_numeric_space($str)
{
return ( ! preg_match(“/^([a-z0-9 ])+$/i”, $str)) ? FALSE : TRUE;
}
}

Now that was easy wasn’t it? You can now use the alpha_numeric_space as one of your validating functions just as you would use alpha_numeric or alpha_dash etc…

CI all the way!

4 Responses to “Adding alpha_numeric_space to the Codeigniter Validation Library”

  1. aryan Says:

    How will you put error message? Thanks for great article.

  2. fil Says:

    Hmm… I added this funciton and am getting this error:
    Parse error: syntax error, unexpected ‘^’ in /html/system/application/libraries/MY_Form_validation.php on line 5

    The syntax looks right to me. Thoughts?

  3. Phil Says:

    @fil I think that’s being caused by the quotes either side of the expression being “curly” quotes when you copy the code to a text editor. Change them and it’ll work… at least, it did for me!

  4. harman Says:

    thanks i also use this…

    you can set error message for this function alpha_numeric_space

    just open
    ../language/english/form_validation_lang.php

    //add this line alpha_numeric_space
    $lang['alpha_numeric_space'] = “YOUR ERROR MSG HERE”

    i hope this work fine.


Leave a Reply