Validating an email field based on a specific domain

I have a site for which the user will need a login. The client gets access only from users of his domain. I need to validate this field based on the email domain address. i.e. only allow email addresses with @ mycompany.com.

Can this be done using the jquery.validate plugin? I see where you can check if it is indeed a valid email, but I would like to make sure it matches a certain pattern (@ mycompany.com).

Any help would be appreciated!

+2


a source to share


2 answers


Just use jQuery validation and compare the string with to make sure the email ends with the expected domain .

This way you know that the email message appears to be valid and has the correct domain.



Here is a possible method for checking a domain. It doesn't really require jQuery.

/**
 * Checks that the user email is of the correct domain.
 * 
 * userInput: potential email address
 * domain:    Correct domain with @, i.e.: "@mycompany.com"
 * Returns:   true iff userInput ends with the given domain.
 */
function checkDomain(userInput, domain) {
        // Check the substring starting at the @ against the domain
        return (userInput.substring(userInput.indexOf('@')) === domain;
}

      

+3


a source


In this example my domain is "@uol.edu.pk". You can do it like this. 


  $(document).ready(function (e) {
                $('#SubmitButton').click(function () {
                    var email = $('#form-email').val();
                    // Checking Empty Fields
                    if ($.trim(email).length == 0 || $("#form-first-name").val() == "" || $("#form-password").val() == "" || $("#Password1").val()=="") {
                        alert('All fields are Required');
                        e.preventDefault();
                    }
                    if (validateEmail(email)) {
                        alert('Good!! your Email is valid');
                    }
                    else {
                        alert('Invalid Email Address');
                        e.preventDefault();
                    }
                });
            });
            // Function that validates email address through a regular expression.
            function validateEmail(pEmail) {
                var filterValue = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
                if (filterValue.test(pEmail)) {
                    if (pEmail.indexOf('@uol.edu.pk', pEmail.length - '@uol.edu.pk'.length) != -1)
                    {
                        return true;
                    }
                    else {
                        alert("Email Must be like(yourName@uol.edu.pk)");
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
    enter code here

      



0


a source







All Articles