Jump to content

Need Help with RegEx


unemployment

Recommended Posts

I'm sorting out my php validation for my sign up but I can't seem to get the regex right for the city field.  What am  I doing wrong? 

 

if (preg_match('#^[A-Za-z ]{1,40} $#i', $city) !== 1)
{
$errors[] = 'City must be between 1 and 40 characters and can contain only letters.';
}

 

I get a validation error when I post "Old World", but shouldn't that be accepted?

Link to comment
https://forums.phpfreaks.com/topic/243479-need-help-with-regex/
Share on other sites

Your pattern has a space between the } and $ which means it looks for 1 to 40 of that stuff in char class, followed by a space.  And since your regex can also contain spaces (it's in your char class and you are saying here that "Old World" should be acceptable) IMO you should update your error message to say it can also have spaces.

 

if (!preg_match('#^[A-Za-z ]{1,40}$#i', $city))
{
$errors[] = 'City must be between 1 and 40 characters and can contain only letters or spaces.';
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.