Isaiah Lee
Isaiah Lee

Reputation: 687

Can't figure out the regex for something so simple

I'm trying to validate a form that's being processed through the POST method in PHP. Some example values being passed are name, age, gender, personality type, etc.

In order to determine whether the user-data that was given is correct, I am using regular expressions.

For example, here's some of the ones that I got to work.. Name (as long as it's not blank, it's fine:

if (strlen($name) == 0) This one worked for me. Another one that worked was the personality type, which had to be of type from the Jung personality test (such as ISTP, ENTP, INFP, etc). My code for that one was: if (!preg_match("/[IE]{1}[NS]{1}[FT]{1}[JP]{1}/", $per)) where $per is the Jung personality type the user submitted. This one also worked fine.

The one that I am having difficulty with is the age. It has to be 0-99, so 1 or 2 digits. I feel like it should be something so simple, but for whatever reason it's not working. Here's the REGEX's I have tried:

/\d{1,2}/

/[0-9]{1,2}/

/(\d|\d\d)/

/([0-9]|[0-9][0-9])/

I don't understand why none of these would work, all four of them seems like it would match the criteria perfectly. Maybe I'm not understanding how to use regexes properly, but I spent the last couple hours perusing examples so I feel pretty confident that it should be correct.

Any help would be greatly appreciated, thanks :)

EDIT: If this helps at all, passing the value "abcdefg" or "ab" as the $age value comes out as an error (which is correct). But, passing the value of "100", or "333", or "99999", comes out as it matching (which is wrong, or it's not what I want). Hope this helps explain a bit more~

Upvotes: 1

Views: 136

Answers (1)

Jonathan Kuhn
Jonathan Kuhn

Reputation: 15301

As has been said, regex is not the right answer for this. But if you have to use regex, you need start ^ and end $ anchors. Regex matches part of a string, so /\d{1,2}/ matches abc123 because it has at least one number with an optional second number. If you want it to match JUST the 2 characters, you need to anchor the match to the start and end of the string like /^\d{1,2}$/ to say "start of string, one or two digits, end of string."

Upvotes: 6

Related Questions