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?



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".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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