0

假设我有两种形式,firstName 和 lastName。

我有一个单独测试的字母数字验证方法。

   function alphaNumericValidation(Name)
   {
     if(/[^a-zA-Z0-9]/.test(firstName.value) || firstName.value == "") 
     {
       Name.style.border = "1px solid red";
       Name.focus();
       return false;
    }
    return true;
   }

现在,我有一个代码提交给的验证方法:

 <td><input type="submit" name="smbt" id="smbt" value="Next" class="nextBtn" onclick="return validation();"/></td>

验证方法写为

  function validation()
  {
    var firstName = document.getElementById("firstName");
    var lastName = document.getElementById("lastName");

    if (alphaNumericValidation(firstName))
    {
        if (alphaNumericValidation(lastName))
        {
            return true;
        }
   }
   else
            return false;

但是逻辑是错误的,它不能按预期工作。我究竟做错了什么?

4

1 回答 1

1

尝试这个:

function alphaNumericValidation(Name) {
  if(/[^a-zA-Z0-9]/.test(Name.value) || Name.value == "") {
    Name.style.border = "1px solid red";
    Name.focus();
    return false;
  }
  return true;
}

您正在测试firstNameinside alphaNumericValidation,它应该在Name那里,因为您将firstName(或lastName)作为Name参数传递给alphaNumericValidation.

编辑

如果仅有效且无效,您的validation()函数不会返回任何内容。firstNamelastName

function validation() {
  var firstName = document.getElementById("firstName");
  var lastName = document.getElementById("lastName");

  if (alphaNumericValidation(firstName)) {
    if (alphaNumericValidation(lastName)) {
      return true;
    }
  // <-- When it gets to here, nothing is returned.. you could add `return false;` here to fix it.
  }
  else
    return false;

试试这个:

if (alphaNumericValidation(firstName) && alphaNumericValidation(lastName)) {
  return true;
}
else
  return false;

编辑 2

你可以继续把 if 语句放在 if 语句中,只要你确保函数总是返回一些东西就可以了。

在你的情况下,我可能会写这样的东西:

function validation() {

  var firstName = document.getElementById("firstName");
  var lastName = document.getElementById("lastName");

  var valid = true;

  valid = valid ? alphaNumericValidation(firstName) : false;
  valid = valid ? alphaNumericValidation(lastName) : false;

  return valid;

}

这将继续运行您的验证,直到其中一个返回false,然后它将跳过之后的验证并validation()返回false

于 2013-04-29T21:15:38.033 回答