Search code examples
phpjqueryemail-validation

jquery mail validation submits the form


I have a jquery to validate my email id,but after validation it submits form instead of preventing it.

my code is

$(document).ready(function(e) {
    $('#personaledits').click(function(e) {
        $('#persemail').each(function(e) {
            email_address = $(this);
            email_regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
            if(!email_regex.test(email_address.val())){  alert('Please enter valid email'); e3.preventDefault(); return e.preventDefault(); return false; } 
        });
    });
});

Solution

  • Try this:

    $(document).ready(function () {  // event is not required here
        $('#personaledits').click(function (e) {
            $('#persemail').each(function () {
                email_address = $(this);
                email_regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
                if (!email_regex.test(email_address.val())) {
                    alert('Please enter valid email');
                    e.preventDefault();    // You need to prevent the click event here
                    return false;
                }
            });
        });
    });