-3

How do I limit the username field upon registration to A-Z and 0-9 for single site? So no spaces, hyphens, underscores, dots etc.

4

Using the regex posted by Moaz (and adding capitals), we will need to hook into the registration_errors filter:

// Restrict username registration to alphanumerics
add_filter('registration_errors', 'limit_username_alphanumerics', 10, 3);
function limit_username_alphanumerics ($errors, $name) {

 if ( ! preg_match('/^[A-Za-z0-9]{3,16}$/', $name) ){
    $errors->add( 'user_name', __('<strong>ERROR</strong>: Username can only contain alphanumerics (A-Z 0-9)','CCooper') );
 }
 return $errors;
}
  • Just a note that this also limits the characters between 3-16. – Christine Cooper Apr 14 '17 at 13:42
1

Use this regular expression

/^[a-z0-9]{3,16}$/

(3,16) used for limit the characters

  • 2
    Out of the box, WordPress enforces a 3-character minimum on usernames. Your {0,16} should probably be {3,16} to reflect this reality. (I had to add a filter to allow a 2-character username.) – Pat J Nov 27 '13 at 17:38

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.