【问题标题】:Checking for alphabet and numeric chars in a field检查字段中的字母和数字字符
【发布时间】:2012-10-10 09:34:27
【问题描述】:

我正在尝试编写 javascript 代码,以确保表单中的字段的前 2 个字符为字母(美国),其余 8 个为数字。

总数必须是10,如果其中任何一个不满意,我应该抛出一个警告框。

我现在正在检查数字,但我不知道如何在同一字段中结合检查字母和数字。

这是我检查数字的代码。

请帮帮我! sid 是我的字段名。

// only allow numbers to be entered
var checkOK = "0123456789";
var checkStr = document.forms[0].sid.value;
var allValid = true;
var allNum = "";

for (i = 0; i < checkStr.length; i++)
{
    ch = checkStr.charAt(i);
    for (j = 0; j < checkOK.length; j++)
        if (ch == checkOK.charAt(j))
            break;

    if (j == checkOK.length)
    {
        allValid = false;
        break;
        if (ch != ",")
            allNum += ch;
    }
    if (!allValid)
    {
        alert("Please enter only 8 numeric characters in the \"sid\" field.");
        return (false);
    }
}    

【问题讨论】:

  • 不能用正则表达式吗?

标签: javascript regex validation


【解决方案1】:

一个正则表达式就可以轻松完成这项检查:

   /^[a-zA-Z]{2}\d{8}$/

/^ 匹配字符串的开头

[a-zA-Z]{2} 完全匹配 2 个字母字符

\d{8} 精确匹配 8 位数字

$/ 匹配字符串结尾

如下使用:

 /^[a-zA-Z]{2}\d{8}$/.test (str)   // Returns true or false

【讨论】:

    【解决方案2】:

    您可以使用正则表达式。 jsfiddle

    var regExp = /[a-z]{2}[0-9]{8}/i;
    
    var text = 'ab12345678'; 
    if(text .replace(/[a-z]{2}[0-9]{8}/i, "").length > 0){
        alert("Please enter only 8 numeric characters in the \"sid\" field.");
        return (false);
    } 
    

    【讨论】:

      【解决方案3】:

      简单的正则表达式,检查 2 个字符 + 8 个数字

      var checkStr = document.forms[0].sid.value;
      if (checkStr.match(/\b[A-z]{2}[0-9]{8}\b/) === null) {
          alert("Please enter only 8 numeric characters in the \"sid\" field.");
          return (false);
      }
      

      【讨论】:

        【解决方案4】:

        /^([a-zA-Z]{2}\d{8})$/; 应检查 2 个字符,然后检查 8 个小数。

        【讨论】:

          猜你喜欢
          • 2018-06-19
          • 2016-02-09
          • 1970-01-01
          • 1970-01-01
          • 2011-08-16
          • 1970-01-01
          • 2012-12-27
          • 1970-01-01
          相关资源
          最近更新 更多