Page 1 of 1

New to regex - help validating a form field

Posted: Tue Jul 25, 2006 7:10 am
by Locust
After reading posts and tutorials about regex I understand the basics and could use regex match function to identify a string.

I have a form which has a field in it. When someone submits the form, I want the script to make sure the field contains only letters (upper or lower case is fine), numbers, and spaces.

I was told regex is able to do this but I'm not sure how.

So far I've tried things along the lines of

Code: Select all

if (preg_match_all('/\w+ +/', $_POST['form_field'])) {return true;}
I'm a little lost

Posted: Tue Jul 25, 2006 7:17 am
by jamiel
This was discussed a bit earlier today here

Posted: Tue Jul 25, 2006 9:08 am
by Locust
Ok I solved it.

For other people looking to do the same thing, this is what I used:

Code: Select all

if (!preg_match('/^[\w\s]+$/', $_POST['form_field']))
{
//fail - it contained invalid characters
echo "This field can contain only numebrs and spaces";}
else {
//sucess
}

Posted: Tue Jul 25, 2006 9:32 am
by feyd
be aware \w covers more than just numbers, \s is more than spaces too.