Specific Domain Email ID Field Validation Using JavaScript And jQuery☑️

A lot of time on the client-side, we need to validate the email address field. So today I will address specific domain email validation. This will help you when you need to fill the textbox with an email from specific domains only. Already there are regular expressions available for general email address validation. You can validate email using remote validation, server validation, and client-side regular expression validation. Today we are covering the client-side validation for a specific domain using Javascript and Jquery.
 
STEP 1
 
First write an html or cshtml code for textbox.
  1. <div class="form-group row">  
  2.    <label for="label-name" class="col-sm-4 col-form-label">Email<span class="Textalert">*</span></label>  
  3.       <div class="col-sm-4">  
  4.          @*if using CSHTML HTML tag helpers   
  5.          @Html.TextBoxFor(m => m.Email, new { @class = "form-control", Id = "myEmail" })*@  
  6.          <input type="text" class="form-control" id="myEmail">  
  7.          <button type="submit" class="btn btn-primary" id="vButton">Verify Email</button>   
  8.       </div>  
  9. </div>  
STEP 2
 
Write following code in JS file and once done include that Script in your HTML file.
  1. $(document).ready(function() {  
  2.     $("#vButton").click(function() {  
  3.         var validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@(domainname.in|domainname.com)$/;  
  4.         var receivedEmail = document.getElementById("myEmail").value.trim();  
  5.         if (!(receivedEmail.toLowerCase().match(validRegex))) {  
  6.             $.alert.open("Please enter valid email address.");  
  7.             return;  
  8.         }  
  9.     });  
  10. });  
That's it. Either add this code in the same file for proof of concept or include this as an external script in your view file. You can change the domain name as per your requirement. In my case, we had multiple domains for our client and they needed these two domain emails to be part of this entry. You can put as many as per your requirement. If it will be an invalid email then the JQuery code will show an alert- "Please enter valid email address".
 
In case the user enters the wrong email then some popup like below will appear.
 
Specific domain Email Id field validation using JavaScript and JQuery☑️
 
In case you don't want domain-specific validation but general validation is needed for your requirement then change the validRegex line to below for general email validation.
 
var validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
 
I hope this article help fellow developers in creating this client-side validation of email address using a regular expression. Let me know in the comments below.