• Resolved wwwolf

    (@wwwolf)


    I need to allow user registrations only for those with email addresses on a single domain. I have tested multiple regular expressions and this one works well in a regex sandbox environment, but as soon as I put it into my functions.php file, it simply rejects all registrations – even email addresses on the correct domain (with the error message below, so it’s definitely this conditional that’s breaking it). Am I:
    a) actually doing something stupid in the regex, even tho the online regex testers say it’s doing what I want?
    b) using a regex syntax that WordPress doesn’t support?
    c) screwing up something in the rest of the function?
    d) misunderstanding the codex, and it’s not as simple as just adding this to functions.php?

    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’ve been staring at this so long now, it could be blindingly obvious and I wouldn’t see it!

    Many thanks!

Viewing 4 replies - 1 through 4 (of 4 total)
  • Thread Starter wwwolf

    (@wwwolf)

    BTW, I’m aware that the regular expression I’ve used doesn’t fully test that a valid email address has been entered – all I need it to do is check that the domain is exactly right (and obviously this isn’t the ‘real’ one!!)

    Moderator bcworkz

    (@bcworkz)

    Regexp patterns in PHP need to include delimiters besides quote marks. Typically a slash is used, but any character not used in the regexp can be used. Whatever the first character is becomes the delimiter. If you want to use a delimiter char within the regexp it can be escaped. Assuming all else is correct (it appears so), this should be your regexp pattern:
    '/( |^)[^ ]+@mydomain\.co\.uk( |$)/'

    Hi wwwolf, Here is a code by which you can validate the email address domain.

    add_filter( 'registration_errors', 'check_email_domain_for_registration', 10, 3 );
    function myplugin_registration_errors( $errors, $sanitized_user_login, $user_email ) {
      if ( !preg_match("/@.*mydomain\.com$/", $user_email) ) {
        $errors->add( 'invalid_email', __( 'ERROR: Only valid "mydomain" email address is allowed.' ));
        $user_email = '';
      }
      return $errors;
    }

    Hope, it helps you.

    Thanks,
    Sami

    Thread Starter wwwolf

    (@wwwolf)

    Many thanks! That worked a treat, though with a slightly more complex regex (for reasons I now can’t entirely remember!)
    ??

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Restrict user registration to emails on a single domain’ is closed to new replies.