Search code examples
phpcodeignitercodeigniter-3

CI Validate request with special characters


I'm using code igniter framework.

How to validate the request that accepts alpha, numeric and special characters.(space, comma,dashes, and forward-slash)

example:

Controller

$this->form_validation->set_rules('address', 'Address', 'required|xss_clean|custom_alpha_numeric');

MY_Form_validation.php

public function custom_alpha_numeric($str)
{
    $valid = (!preg_match("/^[a-z0-9 .,-\-]+$/i", $str)) ? FALSE : TRUE;
    return $valid;
}

is there a way to accept forward slash in my validation?


Solution

  • If you need to search for a meta-character that has special meaning in a regular expression, you need to escape that character. You escape a character using \, so:

    preg_match("/^[a-z0-9 .,-\-\/]+$/i", $str)
    

    In fact you are already doing exactly that for the -, because inside [] that character has special meaning (signifying a range), whereas you want to explicitly match that specific character. You should probably remove the other - in there I think?

    preg_match("/^[a-z0-9 .,\-\/]+$/i", $str)
    

    Alternatively, another option is to use something other than / as the delimiter. From the docs:

    A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.

    If you use a different delimiter, the slash becomes just another character. So for eg using #:

    preg_match("#^[a-z0-9 .,\-/]+$#i", $str)