0

我正在编写一个带有掩码的信用卡字段,但将实际未触及的数字保存到元素的数据属性中。这样,信用卡号“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"); 的值?

关于更好的方法来做到这一点的任何建议?

4

1 回答 1

0

我写了我自己的规则。

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

/* 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; 
});
于 2014-05-16T19:34:26.983 回答