Validating Email Host Before User Registration

In WP, there are so many customization options are available that you can literally do whatever you want. Today I will focus on the user registration system where we will make sure only people with certain email domain name can register. For an example, if you want only people with Gmail address to be able to register on your site, you can easily use this code. This post could be useful for WordPress sites that is highly focused on internal users of a company or organization.

Recently I was working on a website where we strictly wanted only users from our school to be able to register on that site. We wanted to automate this system through the regular WP User Registration form. One good thing about this code is, it won’t bother you while you are doing manual registration from the admin panel.

Here is the snippet:

<?php
function check_email_domain($errors,$sanitized_user_login,$user_email) {
   if (!preg_match("/@gmail.com/",$user_email)) { 
   $errors->add('merror','<strong>ERROR</strong>: Gmail Address Only!');
  }
   return $errors;	
}	
add_filter('registration_errors','check_email_domain', 10,3);
?>

What I have done here is pretty easy to understand. I created a function that takes certain variables from the user registration form and returns an $errors response if the registration form submission doesn’t meet certain criteria. In this case, I am taking the user’s email address as an input and checking if the submission does contain “@gmail.com” within the $user_email variable or not.

Register Error MessageMail Domain Validation Error Message.

I have used the native PHP preg_match function to check the variable. If the user submission doesn’t match with the expected “pattern”, it should send and error message and stops the user registration process. I also used add_filter to hook up my custom function with the registration_errors.

I personally tested this function on my localhost and seems working without any issue. If you want to use this snippet on your site, simply change the “@gmail.com” with your desired host name from the third line. You are good to go.

Today In History

  •  
  •  

Comment

Leave a Reply

Note: Convet HTML, PHP, JavaScripts from HTMLify, before posting from comment section.
License: By submitting a comment here you grant this site a perpetual license to reproduce your words and name/Web site in attribution. Please use your real name or a pseudonym (i.e., pen name, alias, nom de plume) when commenting. If you add your site name, company name, or something completely random, I'll likely change it to whatever I want.