override jquery validate plugin email address validation

前端 未结 4 1160
离开以前
离开以前 2020-11-27 19:31

I find that jQuery validation plugin regex to be insufficient for my requirement. It accepts any email address xxx@hotmail.x as a valid email address whereas I want to be ab

相关标签:
4条回答
  • 2020-11-27 19:33
    // Add Custom Email Validation
    jQuery.validator.addMethod('customemail', function (emailaddr, element) {
          emailaddr = emailaddr.replace(/\s+/g, '');
          return this.optional(element) || 
          emailaddr.match(/^\b[A-Z0-9._%-]+@@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i);
     });
    
    0 讨论(0)
  • 2020-11-27 19:35

    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
                     }
                 }
            });
    
    0 讨论(0)
  • 2020-11-27 19:43

    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
                        },
    
    0 讨论(0)
  • 2020-11-27 19:50

    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

    0 讨论(0)
提交回复
热议问题