Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

override jquery validate plugin email address validation

I find that jQuery validation plugin regex to be insufficient for my requirement. It accepts any email address [email protected] as a valid email address whereas I want to be able to supply this regex /^([a-zA-Z0-9_.-+])+\@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/ so that it would validate complete .com part of the address. I'm more concerned about being able to supply my own regex than getting a fool proof regex(as there is no fool proof regex for email validation)

Just FYI: I'm also doing server side validation but at this point I'm not worried about which email address regex is right.

Is there a way to do that within the "rules" section of jQuery validate plugin?

This is my rules section right now:

rules: {
                        email: {
                            required:  {
                                    depends:function(){
                                        $(this).val($.trim($(this).val()));
                                        return true;
                                    }   
                                },
                            email: true
                        },
like image 479
neelmeg Avatar asked Sep 20 '12 14:09

neelmeg


3 Answers

I wouldn't do this but for the sake of an answer you need to add your own custom validation.

//custom validation rule
$.validator.addMethod("customemail", 
    function(value, element) {
        return /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value);
    }, 
    "Sorry, I've enabled very strict email validation"
);

Then to your rules add:

rules: {
                    email: {
                        required:  {
                                depends:function(){
                                    $(this).val($.trim($(this).val()));
                                    return true;
                                }   
                            },
                        customemail: true
                    },
like image 73
Tom Avatar answered Nov 01 '22 06:11

Tom


Your regex is simply too strict, jQuery is right.

"this is a valid adress !"@yes.it.is

I suggest you to read this : Stop Validating Email Addresses With Your Complex Regex

like image 25
Denys Séguret Avatar answered Nov 01 '22 06:11

Denys Séguret


Try this!

   jQuery.validator.addMethod("customEmail", function(value, element) {
             return this.optional(element) || /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i.test(value);
            }, "Please enter valid email address!");

        $(form).validate({
             rules: {
                 email:{
                     required:true,
                     customEmail:true
                 }
             }
        });
like image 1
Rajesh Karunakaran Avatar answered Nov 01 '22 04:11

Rajesh Karunakaran