Jquery Validator - 验证数据属性中的值

时间:2014-05-16 18:19:40

标签: jquery jquery-validate html5-data

我正在写一个带有遮罩的信用卡字段,但是将实际未触及的数字保存到元素的数据属性中。这种方式的信用卡号码" 6011000000000004"存储使用但是" 601100 ****** 0004"显示在屏幕上。

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

我的表格中有

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

然后当用户更改该值时,它会创建一个掩码并将值保存到$(&#34; #creditcard&#34;)。data(&#34; cc_number&#34;),如:

$(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验证器以验证$(&#34;#creditcard&#34; .data(&#34; cc_number&#34;);

的值

有关更好方法的任何建议吗?

1 个答案:

答案 0 :(得分: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; 
});