Skip to content Skip to sidebar Skip to footer

Issues In Add Validate Email In Javascript

Here is my code:

Solution 1:

For input boxes, you can specify the type as email, and the browser will validate for you.

<input type="email" required>

Or for javascript:

functionvalidate(emailString) {
    return/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(emailString)
}

This will return true if the value for the emailString parameter is a valid email.

Solution 2:

Lets assume you have an input field in your HTML as such -

<form name="emailForm">
    <input type="email"id="email" name="email" />
</form>

In your javascript you can then add an event handler whenever a user activates the text field and then clicks elsewhere (or uses tab to navigate to the next field)

$('#email').blur(function() {
    // Instead of .blur() you can also just have the // form submit event use the checkEmail() function.checkEmail();
});


functioncheckEmail(){
    var email = document.forms["emailForm"]["email"].value;
    var atnum = email.replace(/[^@]/g, '').lengthvar atpos = email.indexOf("@");
    var dotpos = email.lastIndexOf(".");
    if (atpos < 1 || dotpos < atpos + 2 || email.length <= dotpos + 2   || atnum > 1) {
        // E-mail was not valid
        $('#email').css({border: '1px solid #e74c3c'});
        alert("Not a valid e-mail address");
        setTimeout( function() {
            $('#email').css({border: '1px solid #555'});        
        }, 800);
    } else {
        // E-mail was OKalert("You're good to go!");
    }
}

Here's a fiddle

Post a Comment for "Issues In Add Validate Email In Javascript"