WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm facing a problem where I haven't seen proper answer anywhere. What I need help with is this:

How can I prevent my users registering non-alphanumeric usernames? To be exact, I could prevent it by using something like:

function validate_alphanumeric_underscore($string?) { return preg_match('/^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$/',$str); }

But what is the string I should/could use and how can I echo error message saying that the username inputted had invalid characters?


share|improve this question
up vote 0 down vote accepted

Check for alphanumeric

For more details, look at the Q on SO.

$name = 'input string 123";
// Doesn't allow:
// Pre-/Appending white space
// Not more than one space in between
// Non-alphanumeric characters (lower case)
if( ! preg_match( "/^[a-z0-9]+([\\s]{1}[a-z0-9]|[a-z0-9])+$/i", $name ) )
    // Output Error Message
// Or: Does only allow
// Alphanumeric character (lower & upper case)
// Dash & underline "-", "_" - makes (imho) sense
if( ! preg_match( "/^[A-Za-z0-9-_",'\s]+$/", $name ) )
    // Output Error Message

Error Message

You need to do this via Ajax. Best would be to look over the search results. Another (maybe) good reference would be to inspect the code of some ajax login plugins for a "how-to".

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.