unemployment Posted August 1, 2011 Share Posted August 1, 2011 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? Quote Link to comment https://forums.phpfreaks.com/topic/243479-need-help-with-regex/ Share on other sites More sharing options...
requinix Posted August 1, 2011 Share Posted August 1, 2011 Your expression is requiring a space at the end. Quote Link to comment https://forums.phpfreaks.com/topic/243479-need-help-with-regex/#findComment-1250273 Share on other sites More sharing options...
.josh Posted August 1, 2011 Share Posted August 1, 2011 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.'; } Quote Link to comment https://forums.phpfreaks.com/topic/243479-need-help-with-regex/#findComment-1250274 Share on other sites More sharing options...
unemployment Posted August 1, 2011 Author Share Posted August 1, 2011 I fixed it. The space was the issue as it was killing my validation. Thank you. Quote Link to comment https://forums.phpfreaks.com/topic/243479-need-help-with-regex/#findComment-1250283 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.