多个字段上的错误消息验证问题

时间:2017-07-19 09:11:21

标签: javascript validation message

我正在尝试使用简单的JavaScript代码对多个字段进行表单验证。

我面临的问题是,如果我删除public function photoAction(),那么代码运行正常。

return

1 个答案:

答案 0 :(得分:0)

  • 从函数返回时,代码块将终止 进一步执行。

  • 设置var isValid = true;并在每个if..else中更改其值 阻止基于条件和最后的return isValid;

演示 -



function allVal(event) {
  var isValid = true;
  event.preventDefault();
  var numbers = /^[0-9]+$/;
  var letters = /^[A-Za-z]+$/;


  /* matching the number as follows */
  var matchNum = document.form1.text1.value;
  if (matchNum.match(numbers)) {
    document.getElementById("error").innerHTML = "success";
    isValid = true;
  } else if (matchNum.match(letters)) {
    document.getElementById("error").innerHTML = "only numbers allowed";
    isValid = false;
  } else {
    document.getElementById("error").innerHTML = "please enter valid numbers";
    isValid = false;
  }

  /* matching the name as follows */
  var matchName = document.form1.text2.value;
  if (matchName.match(letters)) {
    document.getElementById("error2").innerHTML = "success";
    isValid = true;
  } else {
    document.getElementById("error2").innerHTML = "error";
    isValid = false;
  }

  return isValid;

}

li {
  list-style-type: none;
  font-size: 16pt;
}

.mail {
  margin: auto;
  padding-top: 10px;
  padding-bottom: 10px;
  width: 400px;
  background: #D8F1F8;
  border: 1px soild silver;
}

.mail h2 {
  margin-left: 38px;
}

input {
  font-size: 20pt;
}

input:focus,
textarea:focus {
  background-color: lightyellow;
}

input submit {
  font-size: 12pt;
}

.rq {
  color: #FF0000;
  font-size: 10pt;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>JavaScript form validation - checking all numbers</title>
</head>

<body onload='document.form1.text1.focus()'>
  <div class="mail">
    <h2>Form Valiodation</h2>
    <form name="form1" action="#">
      <ul>
        <!-- enter number in following -->
        <li>
          Enter Number:
        </li>
        <li><input type='text' name='text1' /></li>
        <li class="rq">
          *Enter numbers only.
          <p id="error"></p>
        </li>
        <li>&nbsp;</li>
        <!-- ***************** -->
        <!-- enter name in following -->
        <li>
          Enter Name:
        </li>
        <li id="myList">
          <input type='text' name='text2' />
          <p id="error2"></p>
        </li>
        <li class="rq">
          *Enter alphabets only.
        </li>
        <!-- ***************** -->
        <li>&nbsp;</li>
        <input type="submit" name="submit" value="Submit" onclick="allVal(event)" />
        <li>&nbsp;</li>

      </ul>
    </form>
  </div>
</body>

</html>
&#13;
&#13;
&#13;