JavaScript表单验证自定义消息和最小字段长度

时间:2018-05-10 06:52:18

标签: javascript html forms

我正在尝试使用JavaScript来验证简单表单的输入。有三个领域:

  • 名称是必填文字,不能为空

  • 电子邮件是必填邮箱字段,必须来自域 domain.com.au

  • 邮政编码是必填数字字段,必须为4个字符

我还希望在字段右侧显示自定义错误消息,而不是显示系统弹出窗口。

目前正确验证了前两个字段,但未显示自定义消息。除了必须在其中包含至少一个数字之外,邮政编码字段不会验证。

JavaScript初学者,请善待。



function validation() {
  var emailPattern = new RegExp('\w.%+-]+@domain\.com\.au');

  if (document.getElementById("name").value.length == 0) {
    document.getElementById("nameAlert").innerHTML = "<em> Please enter name here</em>";
    return false;
  } else if (emailPattern.test(document.getElementById("email").value) = false) {
    document.getElementById("emailAlert").innerHTML = "<em> Your email must include @domain.com.au </em>";
    return false;
  } else if (document.getElementById("postcode").value.length != 4) {
    document.getElementById("postcodeAlert").innerHTML = "<em> Your postcode must be four characters long </em>";
    return false;
  } else return true;
}
&#13;
<form method="POST" action="#" onsubmit="return validation();">
  <label for="name">Name</label>
  <input type="text" name="name" id="name"><span id="nameAlert"></span><br><br>
  <label for="email">Email</label>
  <input type="text" name="email" id="email" pattern="[\w.%+-]+@domain\.com\.au"><span id="emailAlert"></span><br><br>
  <label for="postcode">Postcode</label>
  <input type="text" name="postcode" id="postcode" pattern="^[0-9]{4}"><span id="postcodeAlert"></span><br><br>
  <button type="submit">Submit Query</button>
</form>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

你有if语句和else。因此,如果第一个条件为真,则不会检查其他条件,因此只显示一条消息。

以下是一个工作示例

&#13;
&#13;
function validation() {
  var emailPattern = new RegExp('\w.%+-]+@domain\.com\.au');
  var isOk = true;

  if (document.getElementById("name").value.length == 0) {
    document.getElementById("nameAlert").innerHTML = "<em> Please enter name here</em>";
    isOk = false;
  }

  if (emailPattern.test(document.getElementById("email").value) == false) {
    document.getElementById("emailAlert").innerHTML = "<em> Your email must include @domain.com.au </em>";
    isOk = false;
  }

  if (document.getElementById("postcode").value.length != 4) {
    document.getElementById("postcodeAlert").innerHTML = "<em> Your postcode must be four characters long </em>";
    isOk = false;
  }

  return isOk;
}
&#13;
<form method="POST" action="#" onsubmit="return validation();">
  <label for="name">Name</label>
  <input type="text" name="name" id="name"><span id="nameAlert"></span><br><br>
  <label for="email">Email</label>
  <input type="text" name="email" id="email" pattern="[\w.%+-]+@domain\.com\.au"><span id="emailAlert"></span><br><br>
  <label for="postcode">Postcode</label>
  <input type="number" name="postcode" id="postcode" pattern="^[0-9]{4}"><span id="postcodeAlert"></span><br><br>
  <button type="submit">Submit Query</button>
</form>
&#13;
&#13;
&#13;