2015-09-26 82 views
1

我有一個輸入文本到表單中,我寫一個字母數字代碼,我必須驗證。 所以,在我寫的文字,當我提交按鈕點擊使用jQuery驗證輸入文本遵循不同的規則

if there is an error in the text 
    it will be displayed an error message 
else 
    there will be a submit and success message 

的規律可循的:

  • 的代碼的長度必須是27而不是更少而不是更多。

    AA BBÇDDDDD EEEEE FFFFFFFFFFFF

  • AA必須是 「IT」(大寫)。

  • BB是數字(即使是最初的零)。
  • C是一個字符(大寫)。
  • DDDDD是數字(即使是最初的零)。
  • EEEEE是數字(即使是最初的零)。
  • FFFFFFFFFFFF是字符和數字。長度爲12就足夠了。

如何驗證代碼並使用jQuery編寫此規則?

+0

除非你的問題是專門關於這個插件,請不要使用jQuery的驗證標籤。編輯。謝謝。 – Sparky

回答

1

我把一個函數放在一起,幫助您獲得需要使用密碼規則的位置。由於我不確定您如何計劃實現應用程序的這一部分,因此我將留給您以在表單提交中實現它。

更新:我添加了代碼,在檢查規則條件之前從輸入字符串中刪除空格。

原因:如果在輸入中允許空格,則空格將作爲數字檢查的一部分進行計數並返回true。

的jsfiddle Validate Input with Special Rules

測試HTML:

<div id="results"></div> 

測試JavaScript:

/* 
The rules to follow are: 

The length of code must be 27. Not less, not more. 

AA BB C DDDDD EEEEE FFFFFFFFFFFF 

AA must be "IT" (uppercase). first 2 characters 

BB are numbers (even with the initial zero). 3 & 4 characters 
C is a character (uppercase). 5th character 
DDDDD are numbers (even with the initial zero). characters 5 - 10 
EEEEE are numbers (even with the initial zero). characters 11 - 15 
FFFFFFFFFFFF are characters and numbers. It's sufficient that the length is 12. 
characters 16 - 27 above 
*/ 

var input = "IT12C1234567891FFFFFFFFFFFF"; 

validate(input); 


function validate(input){//begin function 

    //remove all of the white space from the input 
    var input = input.replace(/\s+/g, ''); 

    //test for length 
    var testLength = input.length === 27; 

    //2nd and 3rd characters equal IT 
    var AA = input.substring(0,2) === "IT"; 

    //3rd and 4th characters are numbers 
    var BB = !isNaN(input.substring(2,4)); 

    //The 5th character is a non numerical capitalized character 
    var C = isNaN(input.split("")[4]) && input.split("")[4] === input.split("")[4].toUpperCase(); 

    //characters 5 - 10 are numbers 
    var DDDDD = !isNaN(input.substring(5,10)); 

    //characters 11- 15 are numbers 
    var EEEEE = !isNaN(input.substring(10,15)); 

    //characters 16 - 27 can be characters and numbers as long as the length is 12 
    var FFFFFFFFFFFF = input.substring(15,27).length === 12; 

    //if all the password rules checks return true 
    if(testLength && AA && BB && C & DDDDD && EEEEE & FFFFFFFFFFFF){//begin if then 


     //do what you need to do here if the password is valid 

    } 
    else{ 


     //let the user know the error here 


    } 


    //display test results 
    document.getElementById("results").innerHTML = testLength + "<br>" 
     + AA + "<br>" 
     + BB + "<br>" 
     + C + "<br>" 
     + DDDDD + "<br>" 
     + EEEEE + "<br>" 
     + FFFFFFFFFFFF + "<br>"; 



}//end function 
+0

非常感謝你! – Dave

+0

沒問題。看看我所做的更新。還有一個我爲你付的支票,稍後會爲你節省很多麻煩。 –

+0

謝謝!我試圖在複製和粘貼時刪除空格。但它不起作用。 [jsfiddle](https://jsfiddle.net/fzftjz58/),我該如何解決它? – Dave