How to do alphanumeric validation with PHP

Hardly worth a whole blog post but it may help somebody…

is_numeric() is the function to use for validating numeric-only user input with PHP but unfortunately there is no is_alphanumeric(). Or so I thought.

Meet ctype_alnum()

Here’s an example of its usage:

if (ctype_alnum($_POST['username'])) {
    echo "Thanks - that's a good username.";
} else {
    echo "The username must contain only letters and numbers.";

I’ve seen lots of people using regular expressions to get round this, myself included, and it’s not complicated but it’s still nice to simplify where possible.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>