Tag Archives: php

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.