Improve your skills

July 27, 2016

Email Validation in Javascript

Here I will show you how to validate the Email Id using JavaScript or jquery.

First, we take a input text and a input button in body as show in below-

HTML:
<body>
<input id="txtEmail" type="text" placeholder="Email Id" />
<input type="button" value="Check" onclick="return validEmail('txtEmail');" />
</body>

After that, attach the jquery library link on your head part of page and write the below code in head part shown as below-

JS:
<head>
<script src="https://code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function validEmail(id) {
        if ($('#' + id).val() != "") {
            if (/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i.test($('#' + id).val())) {
                alert("Valid email id!");
                return true;
            }
            else {
                alert("Invalid email id, Please enter again!");
                $('#' + id).val('');
                $('#' + id).focus();
            }
        }
        else {
            alert("Please enter email id!");
        }
        return false;
    }
</script>
</head>

Now save the file and run on browser.

when the 'Check' button is clicked then the validEmail() function will be called. It check first text is empty or not, if textbox is empty then show the message 'Please enter email id!' otherwise check the email id and show the message(validate or not).


Result:
Email-validation-in-javascript-or-jquery














Live Demo:




0 comments:

Post a Comment

Subscribe for Latest Update

Popular Posts