0

我正在尝试验证表单字段并且是 javascript 新手。我一直在使用 !isNaN 但这似乎只能检测是否绝对没有数字。例如,在下面的示例中,如果我在输入字段中输入了“Willy,Fred5”,它似乎会检测到字符串并且不会返回 false。我需要做的是检测输入字段中是否有一个数值。但似乎找不到有效的答案。

function fnCheckName(strName) {
    strName.style.background = "#FFFFFF";
    var nameChk = strName.value;
    if (nameChk.indexOf(', ') < 0 || nameChk == "" || !isNaN(nameChk){
        strName.style.background = "#FBEC5D";
        return false}
        else {return true}
4

5 回答 5

2

您需要添加正则表达式:

function fnCheckName(strName) {
strName.style.background = "#FFFFFF";
var nameChk = strName.value;
if (/\d/.test(nameChk)){
        strName.style.background = "#FBEC5D";
        return false
    }
    else {return true}

/^[a-zA-Z]+$/ - 只检查字母(“fdsfjklr”为真)

/^([^0-9]*)$/ - 仅检查数字(“4321”为真)

/\d/ - 检查任何带有数字的字符串(“fdslkj45”为真)

于 2014-05-21T04:47:16.037 回答
2
/\d/.test('foo5')
outputs: true

/\d/.test('foo')
outputs: false

/\d/.test('5')
outputs: true

因此,鉴于这些输入和输出,我认为您修改后的代码将是:

function fnCheckName(strName) {
  strName.style.background = "#FFFFFF";
  var nameChk = strName.value;
  if (nameChk.indexOf(', ') < 0 || nameChk == "" || !/\d/.test(nameChk)) {
    strName.style.background = "#FBEC5D";
    return false
  }
  else {
    return true
  }
}
于 2014-05-21T04:49:18.633 回答
0

试试这个丹雷克斯

function fnCheckName(strName) {
    strName.style.background = "#FFFFFF";
    var nameChk = strName.value;
    var regNew = new RegExp(/^([^0-9]*)$/);
    if (regNew.test(nameChk)) {//If true i.e. no digit is in the string

    } else {//If false i.e. digit is in the string  

    }
}

或者

function fnCheckName(strName) {
        strName.style.background = "#FFFFFF";
        var nameChk = strName.value;
        var regNew = new RegExp(/^([^0-9]*)$/);
        return (regNew.test(nameChk));
    };
于 2014-05-21T04:46:58.440 回答
-1

试试这个改变,

function fnCheckName(strName) {
strName.style.background = "#FFFFFF";
var nameChk = strName.value;
var status = false;
for(var i=0;i<nameChk.length;i++){
  if(isNan(nameChk[i])==false)
    status = true;
  else
    status = false;
}
return status;
}
于 2014-05-21T04:24:18.607 回答
-1

如果你输入一个数字返回 false 否则返回 true

eval('/^[a-zA-Z]+$/').test('sfjd');    

编辑

function fnCheckName(strName) {
        if( eval('/^[a-zA-Z]+$/').test(strName))
        {
            // this name not contains numbers
            // change background or every things that you want
            return true;
        }
        else
        {
            // this name has number or numbers
            // change background or every things that you want
            return false;

        }
    }
于 2014-05-21T04:26:20.597 回答