简体   繁体   English

JavaScript 表单验证一次一个字段

[英]JavaScript Form Validation one field at a time

I need to write a script that does JavaScript validation but i need it to complete one field at a time.我需要编写一个执行 JavaScript 验证的脚本,但我需要它一次完成一个字段。 For example:例如:

I have four fields;我有四个字段; First Name, Last Name, Email, Age名字、姓氏、电子邮件、年龄

If a user clicks the submit field and everything is blank it should only focus on the first field in the form (First Name) it would then throw an error message, focus that box, and turn the field red with a red border.如果用户单击提交字段并且所有内容都是空白的,则它应该只关注表单中的第一个字段(名字),然后它会抛出一条错误消息,聚焦该框,并将该字段变为红色并带有红色边框。

If they fill the First field it would then follow the steps for the second one (last name).如果他们填写第一个字段,它将按照第二个(姓氏)的步骤进行操作。

The only other curve ball is that the age field needs to only allow numbers and they must be between 0-80.唯一的其他曲线球是年龄字段只需要允许数字,并且它们必须在 0-80 之间。

The current script i have is highlighting the forms correctly but it highlights all fields and focuses the last one.我拥有的当前脚本正确突出显示了表单,但它突出显示了所有字段并重点关注最后一个。 Age is also the only field throwing an error.年龄也是唯一抛出错误的字段。 Heres my script:这是我的脚本:

"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);
}

This is the HTML that includes the form:这是包含表单的 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>

So, the issue is, you're checking every value but never breaking out.所以,问题是,您正在检查每个值,但从未突破。 The simplest way is by throwing a return at the end of each of your catch blocks - that way if there IS an error, the function will stop executing instead of moving on and doing the very next check.最简单的方法是在每个 catch 块的末尾抛出一个 return - 这样如果出现错误,该函数将停止执行而不是继续执行下一个检查。

catch(msg) {
  errMsgDiv.style.display = "block";
  errMsgDiv.innerHTML = msg;
  formValidity = false;
  return;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM