【问题标题】:Jquery Validator - validate value in data attributeJquery Validator - 验证数据属性中的值
【发布时间】:2014-05-17 03:34:26
【问题描述】:

我正在编写一个带有掩码的信用卡字段,但将实际未触及的数字保存到元素的数据属性中。这样信用卡号“6011000000000004”被存储起来使用,但屏幕上显示“601100******0004”。

使用 Jquery Validator,有没有办法根据数据属性验证该字段?

在我的表单中

<input type="text" id="creditcard" />

然后当用户更改值时,它会创建一个掩码并将值保存到 $("#creditcard").data("cc_number") 中,例如:

$(document).on("keyup paste drop", "#creditcard", function() {
    // Copy the super secret old cc value */    
    var old_cc = $(this).data("cc_number") || "";

    // Copy the masked value 
    var this_val = $(this).val();

    /* If there is a value and it is less than the max create a mask */ 
    if (this_val.length > 0 && this_val.length <= 16) {
        // If the stored number is less than the new value, 
        // append the last entered character to the stored value.
        // If not make the masked cc # the same as the stored value     
        var cc = (old_cc.length < this_val.length ? old_cc + this_val.substring(this_val.length -1, this_val.length) : old_cc.substring(0,this_val.length));

    // Copy the new cc value to the super secret field
    $(this).data("cc_number", cc);

    /* Code that builds cc_mask
     *  removed to make it easier to read
     */

    // Sets #creditcard value to the mask
    $(this).val(cc_mask);

}

// I don't think we need to do this but since I already have it here...
return false;
});

现在,有没有办法覆盖 jquery 验证器来验证 $("#creditcard".data("cc_number"); 的值;

有什么更好的方法来做到这一点的建议吗?

【问题讨论】:

    标签: jquery jquery-validate html5-data


    【解决方案1】:

    我写了自己的规则。

    基本上我复制了内置的信用卡规则,但让它抓取了我想听的数据元素:

    /* rule to validate a certain data attribute */
    jQuery.validator.addMethod("creditcard_from_datafield", function(value, element, param) {
    if ( this.optional(element) ) {
                return "dependency-mismatch";
            }
            value = $(element).data("cc-number");
    
    
            // accept only spaces, digits and dashes
            if ( /[^0-9 \-]+/.test(value) ) {
                return false;
            }
            var nCheck = 0,
                nDigit = 0,
                bEven = false;
    
            value = value.replace(/\D/g, "");
    
            for (var n = value.length - 1; n >= 0; n--) {
                var cDigit = value.charAt(n);
                nDigit = parseInt(cDigit, 10);
                if ( bEven ) {
                    if ( (nDigit *= 2) > 9 ) {
                        nDigit -= 9;
                    }
                }
                nCheck += nDigit;
                bEven = !bEven;
            }
    
            return (nCheck % 10) === 0; 
    });
    

    【讨论】:

      猜你喜欢
      • 2016-03-19
      • 2021-12-28
      • 2011-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-16
      • 2013-03-30
      • 1970-01-01
      相关资源
      最近更新 更多