Matt W
Matt W

Reputation: 4131

jQuery not validating email format

Quite a specific issue, this jQuery always logging to the console that the email format is invalid despite being a real address. Can't seem to figure out why. Is the regexp correct? Any help is hugely appreciated

    // VALIDATION ON BLUR
    $("#prospects_form > *").blur(function() {

        // Validate Email
        function valEmail() {
            var email = $("#form_email"),
                // Check address format
                emailFilter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

            if (!emailFilter.test(email.value)) {
                // Incorrect
                $("#form_email").addClass("invalid");
                console.log('email invalid');
            } else {
                // Correct
                $("#form_email").removeClass("invalid");
                console.log('email valid');
            }
        }
        valEmail();

    });

Upvotes: 0

Views: 135

Answers (2)

C M
C M

Reputation: 703

jquery Dom object don't have a property value.

use this

$("#form_email").val();

instead of

$("#form_email").value;

Hope this helps....

Upvotes: 1

Moob
Moob

Reputation: 16204

Following my comment:

Seen as var email is a jQuery object you should try email.val() to get its value.

I made this Fiddle showing it working if you use email.val().

if (!emailFilter.test(email.val())) {...

Upvotes: 1

Related Questions