简体   繁体   English

验证功能不起作用

[英]validation function doesn't work

I have created a java script function, it should validate the input character that should contain 10 characters and can contain alphanumeric characters, but this function does not work, please help me 我已经创建了一个Java脚本函数,它应该验证输入字符,该字符应包含10个字符并且可以包含字母数字字符,但是此函数不起作用,请帮帮我

 function ValidateNIC(id) { var letters = /^[0-9a-zA-Z ]+$/; while(id.value.length==10) if(id.value.match(letters)) { return true; } else { alert('NIC must have alphanumeric characters only or should contain 10 charaters'); id.focus(); return false; } } 

With your code as it stands, if the length is not 10, then nothing else happens. 就您的代码而言,如果长度不是10,则什么也不会发生。 A better approach might be: 更好的方法可能是:

if ((id.value.length == 10) && id.value.match(letters)) {
    return true;
}
alert("NIC must ...");
id.focus();
return false;

You can put all the conditions for validation in Regex like ^[a-zA-Z0-9]{10}$ . 您可以在Regex中放置所有验证条件,例如^[a-zA-Z0-9]{10}$ Note that additional {10} in the regex pattern string for creating a match only when the length is 10 exactly . 请注意,正则表达式模式字符串中的附加{10}仅在长度恰好10时用于创建匹配项。

Then you can make use of the Regex Object test method, which test the regex pattern against a string and returns true if the match is successful and false otherwise. 然后,您可以使用Regex Object test方法,该方法针对字符串测试regex模式,如果匹配成功,则返回true ,否则返回false。

Complete modified snippet below with positive and negative test cases. 使用正面和负面的测试用例,完整填写以下经修改的代码段。

 function ValidateNIC(id){ var aphaPattern10 = /^[a-zA-Z0-9]{10}$/g; var result = aphaPattern10.test(id.value); if(!result){ alert('NIC must have alphanumeric characters only or should contain 10 charaters'); //id.focus(); } return result; } var testObjPass = { value : "012345678a"} console.log(ValidateNIC(testObjPass)); var testObjFail = { value : "012345678a21312"} console.log(ValidateNIC(testObjFail)); 

The following code checks the following NIC must have alphanumeric characters only or should contain 10 charaters. 以下代码检查以下NIC必须仅包含字母数字字符或包含10个字符。 So if it is only 10 characters then it will not alert else, it will test the regex. 因此,如果只有10个字符,则不会发出其他警报,它将测试正则表达式。 Considering id is an object with key value 考虑到id是具有键值的对象

  function ValidateNIC(id)
  {
      var letters = /^[0-9a-zA-Z ]+$/;

    if(id.value.length!==10){
      if(id.value.match(letters))
      {
          return true;
      }
      else
      {
          alert('NIC must have alphanumeric characters only or should contain 10 charaters');
          id.focus();
          return false;
      }
      }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM