Restricting Email Input to Business Emails Only using jQuery

Introduction:
When collecting email addresses from users, it’s often essential to ensure that only business or company emails are accepted, excluding personal email addresses like Gmail, Yahoo, or Outlook. This blog post will guide you through a simple yet effective method to achieve this using jQuery.

The Code:
The following code snippet demonstrates how to restrict email input to business emails only, disallowing Gmail addresses:

jQuery(“#email-1 input”).blur(function(){
var text = jQuery(‘#email-1 input’).val();
if( text.indexOf(“gmail.com”) > -1 ) {
jQuery(‘#email-1 input’).after(‘Enter Business Email only’);
} else {
jQuery(‘#email-1 input’).next(‘span’).remove();
}
});

Explanation:

  • jQuery(“#email-1 input”).blur(function(){…}) : This line attaches a blur event listener to the email input field with the ID “email-1”. The function inside the blur event listener will be triggered when the user moves away from the input field.
  • var text = jQuery(‘#email-1 input’).val(); : This line retrieves the value of the email input field.
  • if( text.indexOf(“gmail.com”) > -1 ) {…} : This conditional statement checks if the email address contains “gmail.com”. If it does, the code inside the if statement will be executed.
  • jQuery(‘#email-1 input’).after(‘Enter Business Email only’); : If the email address is a Gmail address, this line adds an error message after the input field, indicating that only business emails are allowed.
  • } else { jQuery(‘#email-1 input’).next(‘span’).remove(); } : If the email address is not a Gmail address, this line removes any existing error messages.

Extending the Code:
To restrict other personal email addresses like Yahoo, Outlook, or Hotmail, you can modify the code to include an array of restricted email domains. Here’s an example:

var restrictedEmailDomains = [“gmail.com”, “yahoo.com”, “outlook.com”, “hotmail.com”];

jQuery(“#email-1 input”).blur(function(){
var text = jQuery(‘#email-1 input’).val();
if( restrictedEmailDomains.some(function(domain) {
return text.indexOf(domain) > -1;
}) ) {
jQuery(‘#email-1 input’).after(‘Enter Business Email only’);
} else {
jQuery(‘#email-1 input’).next(‘span’).remove();
}
});

In this modified code, the restrictedEmailDomains array contains the list of personal email domains to be restricted. The some() method checks if any of the domains in the array are present in the email address. If a match is found, the error message will be displayed.

Conclusion:
By implementing this simple jQuery code, you can effectively restrict email input to business emails only, excluding personal email addresses like Gmail, Yahoo, or Outlook. This is particularly useful for businesses or organizations that require users to provide their official company email addresses.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top