使用jQuery根据不同的规则验证输入文本

时间:2015-09-26 12:56:05

标签: jquery validation

我在表单中输入了一个输入文本,我写了一个字母数字代码,我必须验证。 所以,在我写完文本后,当我点击提交按钮

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 C DDDDD EEEEE FFFFFFFFFFFF

  • AA必须为“IT”(大写)。

  • BB是数字(即使是初始零)。
  • C是一个字符(大写)。
  • DDDDD是数字(即使初始为零)。
  • EEEEE是数字(即使是初始零)。
  • FFFFFFFFFFFF是字符和数字。长度为12就足够了。

如何验证代码并使用jQuery编写此规则?

1 个答案:

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