How to use PHP to validate that input is alphanumeric

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Let’s say that we want to validate that an input from a PHP form is alphanumeric.  We use PHP function preg_match like …

validate alpha numeric

validate alpha numeric

To try out, you can construct page with form that submit to same page.

Here we allowed for underscore but not a space character (such as for an username).  And it needs to be at least one character and max of 10 characters.

The preg_match takes a regular expression and then an input.  If the input matches the regular expression it returns 1.  If not match, it returns 0.  If failure, it returns false.  So if it returns 0 or false, it did not match or failure.  With the negation operator in the if-condition, this throws us in the if clause saying value is not valid.

The regular expression is /^[a-zA-Z]{1,10}$/

The / indicates the start and end of the regular expression.  The ^ indicates the start of string.  The $ indicates the end of string.  What must go in between are the characters [a-zA-Z_]  where a-z are all the lower alphabet and A-Z are all the upper alphabet and plus the _.  We can have anywhere from one to ten of these characters as denoted by {1,10}.

We could have done an case insensitive regular expression like this …

/^[a-z_]{1,10}$/i

Note the “i” indicating “case-insensitive” is outside the / bounding the reg-ex.