jqueryregexjquery-validate

jQuery Validation Email Validation Issues


I am trying to troubleshoot and fix why my email validation is not properly working. It is suppose to detect an invalid email: where it had too many ...(dots), to still except European address (test@tom.uk.tk) as well as test@aol.com. But as of right now its excepting more that one dot, if you don't finish typing as long as it has the @ as long as you don't add the (.) dot. Will someone please help me with where I am going wrong?

<script>
     $("#form").validate({
    rules: {
        firstname_1: {
            required: true
        },
        email_1: {
            required: true,
            email: true
        },
        // Same for other fields
    },
    messages: {
        firstname_1: "This field is required.",
        email_1>: "Please enter valid email address.",
        // Repeat for other fields
    }
});
function isValidEmail(email_1)
{
    return /^[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,4}$/.test(email_1)
        && /^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*/.test(email_1);
}
</script>

Solution

  • Assuming you already have the correct validation logic and/or regex, then you would need to create your own rule using the .addMethod() method.

    $("#form").validate({
        rules: {
            firstname_1: {
                required: true
            },
            email_1: {
                required: true,
                myEmail: true  // <- declare your custom rule
            },
            // Same for other fields
        },
        messages: {
            firstname_1: "This field is required.",
            email_1: "Please enter valid email address.",
            // Repeat for other fields
        }
    });
    
    // create your custom rule
    jQuery.validator.addMethod("myEmail", function(value, element) {
        return this.optional(element) || /* your regex boolean logic goes here */;
    }, 'Please enter valid email address.');
    

    NOTE: You also had a syntax/spelling error on a field name within messages. Should be email_1, not email_1>.

    See this answer for the proper way to use .addMethod().