Skip to content Skip to sidebar Skip to footer

Validate/accept Only Emails From A Specific Domain Name

This is part of my jQuery script. I need to make the system validate emails for a specific domain. like example@schooldomain.com And only allow emails from @schooldomain.com Code:

Solution 1:

Firstly, as pointed out in the comments, validate the email using regex, and then check if the email is from the right domain.

functionvalidateEmail(email) { 
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    if(re.test(email)){
        //Email valid. Procees to test if it's from the right domain (Second argument is to check that the string ENDS with this domain, and that it doesn't just contain it)if(email.indexOf("@thedomain.com", email.length - "@thedomain.com".length) !== -1){
            //VALIDconsole.log("VALID");
        }
    }
}

Solution 2:

Thanks to this thread I found another solution for only accepting one specific domain after the "at" / "@". Get everything after the dash in a string in JavaScript Basically dividing the email in two, the text before @ and the text after @. If the text after @ is not equal to the specified domain the validation will be false.

// Email validation   let em = document.forms['Login']['email'].value; 
let atpos = em.indexOf("@");
let domain = em.split("@")[1]; // Saves user input after the @ (at)if (em == null || em == "") {
    alert("Email can not be empty.");
    document.getElementById('e').focus();
    returnfalse;
} 
                                            // First test checks for atleast one character before @elseif (atpos < 1 || domain != "gmail.com"){ // Second test checks if the user entered a gmail.com domain after @alert("Not a valid e-mail address. Please write your gmail address like this: username@gmail.com.");
    document.getElementById('e').focus();
    returnfalse;
} 

Post a Comment for "Validate/accept Only Emails From A Specific Domain Name"