Welcome Guest, Not a member yet? Register   Sign In
whitespace in validation
#1

[eluser]Vikeoar[/eluser]
I'm validating a form and using the alpha_dash method with the validation library.

How do I allow for white space in a name? ie. "firstname lastname" without the quotes of course. I tried the trim method but the validation still gets stuck on the name field.

Is there a better method to validate a name that contains whitespace?

I suppose I could break the form up into two separate fields, firstname and lastname.

Any thoughts?

Thanks in advance.
#2

[eluser]Seppo[/eluser]
I can't find any built-in function to do it... You can extend your validation class to create a method for this purpose

Code:
<?php
class MY_Validation extends CI_Validation {
    /**
     * Alpha-numeric with underscores, dashes and spaces
     *
     * @access    public
     * @param    string
     * @return    bool
     */    
    function alpha_dash_space($str)
    {
        return ( ! preg_match("/^([-a-z0-9_- ])+$/i", $str)) ? FALSE : TRUE;
    }
    
}
?>
#3

[eluser]Derek Allard[/eluser]
That's a nice re-useable solution. If you just need a one-off, consider using a callback.
#4

[eluser]xwero[/eluser]
added it to the wiki page MY_Validation
#5

[eluser]Vikeoar[/eluser]
Thanks everyone. Seppo: that did the trick. I had read a bit about extending validation, but I'm new to CI so I wasn't quite sure how to put it together, or whether that was the right way to go.

Thanks again!

On a side note: being new to CI I have to say I'm impressed with the documentation, the wiki, and especially this forum. I've been able to accomplish a lot in just a few days. The community has been very helpful.
#6

[eluser]Flemming[/eluser]
I found that the solution described above and in the wiki for validating alpha numeric with spaces gave me the following error:
Code:
preg_match() [function.preg-match]: Compilation failed: range out of order in character class at offset...

so i changed the regex to the following:

Code:
return ( ! preg_match("/^([-a-z0-9_-\s])+$/i", $str)) ? FALSE : TRUE;

using a '\s' instead of an empty space

and that cured it.
#7

[eluser]SeanJA[/eluser]
Ah, and if you have trouble with regex matching (or you are lazy like me), http://www.txt2re.com/index.php3




Theme © iAndrew 2016 - Forum software by © MyBB