jQuery Validate 不作用于自定义验证值

Posted

技术标签:

【中文标题】jQuery Validate 不作用于自定义验证值【英文标题】:jQuery Validate not acting on custom validation value 【发布时间】:2021-08-21 23:44:58 【问题描述】:

TLDR 版本:我有一个自定义 jquery 验证,它返回正确的值,但规则没有得到执行。

我有一个如下所示的自定义验证规则:

$.validator.addMethod("isDomainValid", function(value, element) 
        var domain = value.split("@");
        $.get('/api/validate-domain/' + domain[1], function(data, status) 
            domain = JSON.parse(data);
            console.log(domain['status'] === 'valid');
            return (domain['status'] === 'valid');
        );
    );

此验证调用一个 php API 来检查电子邮件的域名是否有效,因此是正确的。此 API 返回正确的值,并且 console.log() 也反映了正确的值,这是我作为布尔值返回的值。到目前为止一切顺利...

我这样称呼这个验证规则:

validator.validate(
    rules: 
        email: 
            required: true,
            email: true,
            isDomainValid: true,
        ,
);

我还有一些自定义错误消息(我认为可能无关紧要),如下所示:

messages: 
            email: 
                required: "The Email Address cannot be empty",
                isDomainValid: "Please correct the Email Address after the @ character",
                email: "Invalid Email Address format",
            , ,

我所有的验证,包括另一个自定义验证,除了这个之外都完美无缺。这是我正在运行的所有代码,以防有人想查看整个内容。同样,除了自定义 isDomainValid 验证之外,所有验证都有效。

    var validator = $('#checkout_form');
    
    $.validator.addMethod("checkPoBox", function(value, element) 
        let cleansedValue = $.trim(value.toLowerCase()).replace(/[^a-zA-Z]+/g, '');
        let checked = $('#ship-box').prop('checked') ? true : false;
        if (/pobox/i.test(cleansedValue) && checked && element.name == 'shipping_address') 
            return false;
        
        if (/pobox/i.test(cleansedValue) && !checked && element.name == 'billing_address') 
            return false;
        
        return true;
    );
    
    $.validator.addMethod("isDomainValid", function(value, element) 
        var domain = value.split("@");
        $.get('/api/validate-domain/' + domain[1], function(data, status) 
            domain = JSON.parse(data);
            console.log(domain['status'] === 'valid');
            return (domain['status'] === 'valid');
        );
    );
    
    validator.validate(
        rules: 
            email: 
                required: true,
                email: true,
                isDomainValid: true,
            ,
            billing_first_name: 
                required: true
            ,
            billing_last_name: 
                required: true
            ,
            billing_address: 
                required: true,
                checkPoBox: true
            ,
            billing_city: 
                required: true
            ,
            billing_state: 
                required: true
            ,
            billing_zip: 
                required: true,
                minlength: 5,
                maxlength: 5,
                digits: true
            ,
            billing_phone: 
                required: true,
                minlength: 10,
                maxlength: 10,
                digits: true
            ,
            name_on_credit_card: 
                required: true
            ,
            credit_card_number: 
                required: true,
                creditcard: true
            ,
            expiration_month: 
                required: true
            ,
            expiration_year: 
                required: true
            ,
            cvv: 
                required: true,
                minlength: 3,
                maxlength: 4,
                digits: true
            ,
            shipping_first_name: 
                required: function () 
                    return $('#ship-box').prop('checked');
                
            ,
            shipping_last_name: 
                required: function () 
                    return $('#ship-box').prop('checked');
                
            ,
            shipping_address: 
                required: function () 
                    return $('#ship-box').prop('checked');
                ,
                checkPoBox: true
            ,
            shipping_city: 
                required: function () 
                    return $('#ship-box').prop('checked');
                
            ,
            shipping_state: 
                required: function () 
                    return $('#ship-box').prop('checked');
                
            ,
            shipping_zip: 
                required: function () 
                    return $('#ship-box').prop('checked');
                ,
                minlength: 5,
                maxlength: 5,
                digits: true
            ,
            shipping_phone: 
                required: function () 
                    return $('#ship-box').prop('checked');
                ,
                minlength: 10,
                maxlength: 10,
                digits: true
            
        ,
        messages: 
            email: 
                required: "The Email Address cannot be empty",
                isDomainValid: "Please correct the Email Address after the @ character",
                email: "Invalid Email Address format",
            ,
            billing_first_name: "First Name cannot be blank",
            billing_last_name: "Last Name cannot be blank",
            billing_address: 
                required: "Address cannot be blank",
                checkPoBox: "Products cannot be shipped to a P.O. Box"
            ,
            billing_city: "Town/City cannot be blank",
            billing_state: "Please select a State",
            billing_zip: "Please enter a valid 5 digit Zip Code",
            billing_phone: "Please enter a valid 10 digit Phone Number",
            name_on_credit_card: "Name on Card cannot be blank",
            credit_card_number: "Please enter a valid Credit Car Number",
            expiration_month: "Please select an Expiration Month",
            expiration_year: "Please select an Expiration Year",
            cvv: "Please enter a valid 3 or 4 digit CVV",
            shipping_first_name: "First Name cannot be blank",
            shipping_last_name: "Last Name cannot be blank",
            shipping_address: 
                required: "Address cannot be blank",
                checkPoBox: "Products cannot be shipped to a P.O. Box"
            ,
            shipping_city: "City cannot be blank",
            shipping_state: "Please select a State",
            shipping_zip: "Please enter a valid 5 digit Zip Code",
            shipping_phone: "Please enter a valid 10 digit Phone Number",
        ,
        invalidHandler: function(event, validator) 
            if(validator.numberOfInvalids() > 0) 
                event.preventDefault();
                $('button#place_order_btn').text("PLACE ORDER");
                return false;
            
        ,
        submitHandler: function (validator) 
            validator.submit();
        
    );

任何帮助将不胜感激。

【问题讨论】:

【参考方案1】:

我认为您遇到了一个问题,即成功回调函数的返回值在 $.get 方法中丢失。根据我的经验,在以类似方式检查服务器时,我不得不手动触发错误作为回调的一部分。

另外,我在四处挖掘并找到了一些 jQuery 验证文档,似乎它可以让您尝试做的事情变得更容易:https://jqueryvalidation.org/remote-method/

尝试更新rules.email 属性,替换isDomainValid

  rules: 
    email: 
      required: true,
      email: true,
      remote: 
        url: function() 
          var value = $("[name='email']").val();
          var domain = value.split("@");
          return "/api/validate-domain/" + domain[1];
        ,
      
    ,

您可以删除对注册“isDomainValid”方法的$.validator.addMethod 的调用。

另外,不要忘记在别处更新isDomainValid,将其替换为remote,这样消息是正确的。

  messages: 
    email: 
      required: "The Email Address cannot be empty",
      email: "Invalid Email Address format",
      remote: "Please correct the Email Address after the @ character",
    ,

【讨论】:

以上是关于jQuery Validate 不作用于自定义验证值的主要内容,如果未能解决你的问题,请参考以下文章

jquery.validate怎么不起作用

jQuery Validate 验证但不提交

jquery.validate.js第一次提交验证不起作用,刷新之后再提交才起作用,请各位帮忙看看是怎么回事!

jquery.validate.js使用之自定义表单验证规则

表单验证——jquery validate使用说明

无法使用 jQuery validate 验证我的表单