locked
How to validate Email Domain extensions using JQuery. RRS feed

  • Question

  • User-930371450 posted

    Hi Team,

    Can you please provide  a solutions for How to validate email Domain extensions using JQuery. 

    1. .com
    2. .org
    3. co.in
    4. .net

    if we enter the email like below example then it should validate

    abc@gmail.or--- incorrect email address

    abc@gmail.org -- correct email address

    Wednesday, July 8, 2020 9:39 AM

All replies

  • User-1330468790 posted

    Hi SSK_Nani,

    You could simply use Regex to complete the validation as long as you have an allow-list for the domain extensions. 

    var EMAIL_REGEX = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.((com)|(org)|(co.in)|(net))$/;

    If you really want to validate the Email Domain extensions using JQuery, you might mean using JQuery Validation plugin. You will still need to set up your own email validation function as custom email.

    $.validator.addMethod("customemail", 
        function(value, element) {
            return /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.((com)|(org)|(co.in)|(net))$/.test(value);
        }, 
        "Sorry, the domain extension is not allowed."
    );

    $("#input").validate({ rules: { Email: { required: true, customemail: true } }, });

    Below is a demo that proves how you could use the Regex.

    html:

    <input id="emailAddress" type="text" >
    <input type="button" value="Check" onclick="emailCheck()">
    <label id="result" ></label>

    Javascript:

    var EMAIL_REGEX = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.((com)|(org)|(co.in)|(net))$/;
    
    function emailCheck()
    {
        var email = document.getElementById("emailAddress").value;
        
        document.getElementById("result").innerText = EMAIL_REGEX.test(email) == true ? 'valid' : 'invalid'
        
    }

    You could test the codes in this jsfiddle.

     

    Hope this can help you.

    Best regards,

    Sean

    Wednesday, July 8, 2020 12:54 PM