Restrict user registration to emails on a single domain

You need to use delimiters in order for your regex to work.

From the link above

When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.

so in your case, you could have something like this. Notice how I used the / to delimit the regex

add_filter( 'registration_errors', 'myplugin_registration_errors', 10, 3 );
function myplugin_registration_errors( $errors, $sanitized_user_login, $user_email ) {

  if (! preg_match('/( |^)[^ ]+@mydomain\.co\.uk( |$)/', $user_email )) {
    $errors->add( 'invalid_email', __( 'ERROR: Only valid "mydomain" email address is allowed.' ));
    $user_email="";
  }

  return $errors;
}

I notice you allow white space at the beginning and the end of your regex.

Maybe you want to use this regex to avoid allowing whitespace (unless this is the desired outcome)

if (! preg_match('/^[a-zA-Z0-9._-]+@mydomain\.co\.uk$/', $user_email )) {

  • ^ means starting from
  • [a-zA-Z0-9._-] means any alphanumerical caracter and dot . underscore _ and dash - characters are allowed
  • + means one or more of the preceding token, [] in this case
  • \. escapes the dot so it’s not interpreted as any characters
  • $ means ending here

also note that since you filter into WP registration validation mechanism, you are adding to the current check, so technically, WP will check if this is a valid email on top of what you are asking

Leave a Comment