JavaScript表单验证一次一个字段

时间:2018-10-16 14:37:53

标签: javascript html forms

我需要编写一个脚本来执行JavaScript验证,但是我需要一次完成一个字段。例如:

我有四个领域;名,姓,电子邮件,年龄

如果用户单击“提交”字段,而所有内容均为空白,则应仅将焦点放在表单(“名字”)中的第一个字段上,然后将引发错误消息,将其聚焦,然后将该字段变为红色并带有红色边框。

如果他们填写“第一个”字段,则将遵循第二个(姓氏)的步骤。

唯一的另一个曲线球是age字段只需要允许数字,并且它们必须在0-80之间。

我当前使用的脚本正确地突出显示了表单,但是突出显示了所有字段并集中了最后一个字段。年龄也是唯一一个引发错误的字段。这是我的脚本:

"use strict";

var deptList = ["SDEV","DBMS","INFM","CSCI","SVAD","NETI","ITSP","CSIA"];
var list = document.getElementById("progList");
var formValidity = true;
var errMsgDiv = document.getElementById("errorMsg");
function createCheck() {
    deptList.sort();
    for (var i = 0; i <= 7; i++) {
        (function(i) {
        var boxText = deptList[i];
        var deptEntry = document.createElement ("label");
        deptEntry.innerHTML = "<input type=checkbox name=programs[] value=" + i + " />" + boxText;
        list.appendChild (deptEntry);
        console.log("deptEntry");
  })(i);
 }
}
function validateInput(evt) {
  if (evt.preventDefault) {
    evt.preventDefault(); // prevent form from submitting
  } else {
    evt.returnValue = false; // prevent form from submitting in IE8
  }
  formValidity = true; // reset value for revalidation
  checkBlank();
  validateNumbers(); // additional
  if (formValidity === true) {
    document.getElementsByTagName("form")[0].submit();
  }
}
function createEventListeners() {
  var form = document.getElementsByTagName("form")[0];
   if (form.addEventListener) {
    form.addEventListener("submit", validateInput, false);
  } else if (form.attachEvent) {
    form.attachEvent("onsubmit", validateInput);
}
}
function checkBlank() {
  var chkBlnkVal = true;
  var fName = document.forms[0].fname;
  var lName = document.forms[0].lname;
  var email = document.forms[0].email;
  console.log("Entering checkBlank " + "form validity: " + formValidity +" check blank validity: " + chkBlnkVal);
 try { 
  if (fName.value === ''){
    fName.style.background = "rgb(255,233,233)";
    fName.style.borderColor = "red";
    chkBlnkVal = false;
    fName.focus();
  } else {
    fName.style.background = "white";
    fName.style.borderColor = "white";
  }
 if (chkBlnkVal === false) {
    throw "Please complete all fields.";
    }
    errMsgDiv.style.display = "none";
    errMsgDiv.innerHTML = "";
  }
 catch(msg) {
 errMsgDiv.style.display = "block";
 errMsgDiv.innerHTML = msg;
 formValidity = false;
 }
  try { 
  if (lName.value === ''){
    lName.style.background = "rgb(255,233,233)";
    lName.style.borderColor = "red";
    chkBlnkVal = false;
    lName.focus();
  } else {
    lName.style.background = "white";
    lName.style.borderColor = "white";
  }
 if (chkBlnkVal === false) {
    throw "Please complete all fields.";
    }
    errMsgDiv.style.display = "none";
    errMsgDiv.innerHTML = "";
  }
 catch(msg) {
 errMsgDiv.style.display = "block";
 errMsgDiv.innerHTML = msg;
 formValidity = false;
 }
 try { 
  if (email.value === ''){
    email.style.background = "rgb(255,233,233)";
    email.style.borderColor = "red";
    chkBlnkVal = false;
    email.focus();
  } else {
    email.style.background = "white";
    email.style.borderColor = "white";
  }
 if (chkBlnkVal === false) {
    throw "Please complete all fields.";
    }
    errMsgDiv.style.display = "none";
    errMsgDiv.innerHTML = "";
  }
 catch(msg) {
 errMsgDiv.style.display = "block";
 errMsgDiv.innerHTML = msg;
 formValidity = false;
 }
 console.log("Leaving checkBlank " + "form validity: " + formValidity +" check blank validity: " + chkBlnkVal +" First Name: " + fName.value);
}

function validateNumbers() {
  var numbersValidity = true;
  var age = document.forms[0].age;
  try {
  if (isNaN(age.value) || (age.value
      === "") || (age.value <= -1) || (age.value >= 81)) {
    age.style.background = "rgb(255,233,233)";
    age.style.borderColor = "red";
    numbersValidity = false;
    age.focus();
  } else {
    age.style.background = "white";
    age.style.borderColor = "white";
  }
  if (numbersValidity === false) {
    throw "Please enter valid number for age.";
    }
    errMsgDiv.style.display = "none";
    errMsgDiv.innerHTML = "";
  }
 catch(msg) {
 errMsgDiv.style.display = "block";
 errMsgDiv.innerHTML = msg;
 formValidity = false;
 }
 console.log("Leaving validateNumbers " + "form validity: " + formValidity +" numbers validity: " + numbersValidity +" age: " + age.value);
}
function init(){
    createEventListeners();
    createCheck();
}

if (window.addEventListener) {
   console.log("> Adding TC39 Event Listener...");
   window.addEventListener ("load", init, false);
}
else if (window.attachEvent) {
   console.log("> Adding MS Event Listener...");
   window.attachEvent ("onload", init);
}

这是包含以下形式的HTML:

<form action="exam01.php" method="post" novalidate=novalidate>
<h2>School of Information Technology Membership Form</h2>
<p id="errorMsg"></p>
<fieldset id="left">
 <legend>Contact Info</legend>
 <p><span class="grid3">Name</span>
    <span class="grid1"><input type="text" name="fname" placeholder="First Name" size="15" maxlength="25" autofocus /></span>
    <span class="grid1"><input type="text" name="lname" placeholder="Last Name" size="15" maxlength="25" /></span>
 </p>
 <p><span class="grid3">eMail</span>
    <span class="grid2"><input type="email" name="email" placeholder="user@domain.com" size="35" /></span>
 </p>
 <p><span class="grid3">Age</span>
    <span class="grid2"><input type="number" name="age"  /></span>
 </p> 
</fieldset>
<fieldset id="right">
 <legend>Programs</legend>
 <p class="twoColumn" id="progList"></p>
</fieldset>
<p id="submit"><input type="submit" name="btnSubmit" value="Submit" /></p>
</form>

1 个答案:

答案 0 :(得分:-1)

因此,问题是,您正在检查每个值,但从未突破。最简单的方法是在每个catch块的末尾抛出一个返回值-这样,如果发生错误,该函数将停止执行,而不是继续执行下一个检查。

"128"