New to regex - help validating a form field

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
Locust
Forum Commoner
Posts: 31
Joined: Sat Jul 22, 2006 10:26 am

New to regex - help validating a form field

Post 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
jamiel
Forum Contributor
Posts: 276
Joined: Wed Feb 22, 2006 5:17 am
Location: London, United Kingdom

Post by jamiel »

This was discussed a bit earlier today here
Locust
Forum Commoner
Posts: 31
Joined: Sat Jul 22, 2006 10:26 am

Post 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
}
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

be aware \w covers more than just numbers, \s is more than spaces too.
Post Reply