2014-05-16 3 views
0

마스크가있는 신용 카드 필드를 작성하지만 요소의 데이터 속성에 실제 변경되지 않은 번호를 저장합니다. 이렇게하면 신용 카드 번호 "6011000000000004"는 사용하기 위해 저장되지만 "601100 ****** 0004"이 화면에 표시됩니다.Jquery Validator - 데이터 속성의 값 유효성 확인

Jquery Validator를 사용하면 데이터 속성을 기반으로 해당 필드의 유효성을 검사 할 수 있습니까? 내 양식에

나는 사용자가 값을 변경할 때

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

다음,이 마스크를 만들고 $ ("#의 크레딧 카드")로 값을 절약 할 수있는 등의 데이터 ("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; 
}); 

지금, $ ("#의 크레딧 카드".DATA ("cc_number을")의 값을 검증하기 위해 JQuery와 유효성 검사기를 무시하는 방법은 무엇입니까?

답변

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; 
});