【问题标题】:Javascript function not passing parameters after form is submitted (form validation)提交表单后Javascript函数不传递参数(表单验证)
【发布时间】:2020-06-16 05:23:21
【问题描述】:

在单击提交按钮之前,我的表单验证工作正常。

单击提交按钮后,Java 表单验证将中断。

好像java onfocusoutfunction(见下文)在提交后没有发送参数。您可以在下面保存的笔中遇到错误:

https://codepen.io/h0ttamale/pen/MWKjrYZ

function validateNameField(inputDivId, errDivId) {
  var inputValue = document.getElementById(inputDivId).value;
  if (inputValue == "") {
    printError(errDivId, "What's your first name?");
    document.getElementById(errDivId).style.display = "none"; //could I use jQuery hide()? I don't want to report error if blank until submit (for UX)

  } else {
    var regex = /^[a-zA-Z]{2,}$/;
    if (regex.test(inputValue) === false) {
      printError(errDivId, "Valid names don't contain spaces"); //function is in formvalidation.js file
    } else {
      printError(errDivId, "");
      nameErr = false;
      document.getElementById(errDivId).style.display = "none"; //could I use jQuery hide()?
    }
  }
}

// Validate email address
function validateEmailField(inputDivId, errDivId) {
  var inputValue = document.getElementById(inputDivId).value;

  if (inputValue == "") {
    printError(errDivId, "What's your email?");
    document.getElementById(errDivId).style.display = "none"; //could I use jQuery hide()? I don't want to report error if blank until submit (for UX)

  } else {
    // Regular expression for basic email validation
    var regex = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}/;
    if (regex.test(inputValue) === false) {
      printError(errDivId, "Valid emails don't contain any typos");
    } else {
      printError(errDivId, "");
      emailErr = false;
      document.getElementById(errDivId).style.display = "none"; //could I use jQuery hide()?
    }
  }
}

// JavaScript Document

// Defining a function to display error message
function printError(elemId, hintMsg) {
  document.getElementById(elemId).innerHTML = hintMsg;
  document.getElementById(elemId).style.display = "block"; //could I use jQuery show()?
}

// Defining a function to validate form 
function validateForm() {

  // Defining error variables with a default value. True means there are errors and form won't be submitted.
  var fnameErr = lnameErr = emailErr = true;

  // Validate fname
  if (typeof document.InviteForm.fname !== "undefined") {
    var fname = document.InviteForm.fname.value;

    if (fname == "") {
      printError("fnameErr", "What's your first name?");
    } else {
      var regex = /^[a-zA-Z]{2,}$/;
      if (regex.test(fname) === false) {
        printError("fnameErr", "Valid names don't contain spaces");
      } else {
        printError("fnameErr", "");
        fnameErr = false;
        document.getElementById("fnameErr").style.display = "none"; //could I use jQuery hide()?
      }
    }
  }
  // Validate fname
  if (typeof document.InviteForm.lname !== "undefined") {
    var lname = document.InviteForm.lname.value;

    if (lname == "") {
      printError("lnameErr", "What's your last name?");
    } else {
      var regex = /^[a-zA-Z]{2,}$/;
      if (regex.test(lname) === false) {
        printError("lnameErr", "Valid names don't contain spaces");
      } else {
        printError("lnameErr", "");
        lnameErr = false;
        document.getElementById("lnameErr").style.display = "none"; //could I use jQuery hide()?

      }
    }
  }

  // Validate email address
  if (typeof document.InviteForm.email !== "undefined") {
    var email = document.InviteForm.email.value;

    if (email == "") {
      printError("emailErr", "What's your email?");
    } else {
      // Regular expression for basic email validation
      var regex = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}/;
      if (regex.test(email) === false) {
        printError("emailErr", "Valid emails don't contain any typos");
      } else {
        printError("emailErr", "");
        emailErr = false;
        document.getElementById("emailErr").style.display = "none"; //could I use jQuery hide()?
      }
    }
  }

  // Prevent the form from being submitted if there are any errors

  if ((fnameErr || lnameErr || emailErr) == true) {
    return false;
  } else {
    // Creating a string from input data for preview
    var dataPreview = fname + lname + email;

    // Display input data in a dialog box before submitting the form
    alert(dataPreview);
  }
};
/* ----------> FORM <---------- */

.inviteformcontainer {
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  flex-direction: column;
  position: relative;
  height: calc(100vh - 6em);
}

.inviteform {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  width: 50vw;
  grid-column-gap: 2em;
}

.firstname {
  grid-column: 1/3;
}

.lastname {
  grid-column: 3/5;
}

.inputcontainer {}

.error {
  font-family: inherit;
  border: 1px solid #f47b22;
  background: #fafafa;
  color: #f47b22;
  font-family: sans-serif;
  font-size: .75em;
  padding: 1em 1em;
  height: 3em;
  box-sizing: border-box;
  width: 100%;
  margin-bottom: 1em;
  display: none;
}

.email {
  grid-row: 2/3;
  grid-column: 1/5;
}

.submit {
  grid-row: 3/4;
  grid-column: 2/4;
  justify-self: center;
}

.button {
  font-family: futura;
  font-size: 1em;
  font-weight: 700;
  letter-spacing: .26em;
  font-style: normal;
  text-transform: uppercase;
  color: white;
  border: 0;
  background-color: #f47b22;
  border-color: #f47b22;
  border-style: solid;
  padding: 2em 3em;
  text-align: center;
  text-decoration: none;
  cursor: pointer;
  -webkit-appearance: none;
  -moz-appearance: none;
  place-self: center;
}

.button:hover {
  background-color: #f48f22;
  border-color: #f48f22;
  border-style: solid;
  border: 0;
}

input[type=text],
input[type=number],
input[type=email] {
  font-family: inherit;
  border: 1px solid #ccc;
  background: #fafafa;
  color: #000;
  font-family: sans-serif;
  font-size: 1em;
  padding: 2em 1em;
  height: 3em;
  box-sizing: border-box;
  width: 100%;
}

input:invalid {
  box-shadow: none;
}
<form name="InviteForm" class="inviteform" method="post">
  <div class="firstname inputcontainer">
    <input type="text" id="firstname" name="fname" placeholder="First Name*" required pattern="[a-zA-Z]{2,}" onfocusout="validateNameField(this.id, fnameErr.id)">
    <div class="error" id="fnameErr"></div>
  </div>
  <div class="lastname inputcontainer">
    <input type="text" id="lastname" name="lname" placeholder="Last Name*" required pattern="[a-zA-Z]{2,}" onfocusout="validateNameField(this.id, lnameErr.id)">
    <div class="error" id="lnameErr"></div>
  </div>
  <div class="email inputcontainer">
    <input type="email" id="email" name="email" placeholder="Email*" required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}" onfocusout="validateEmailField(this.id, emailErr.id)">
    <div class="error" id="emailErr"></div>
  </div>
  <input class="button submit" id="submit" type="submit" value="Get Invited" onsubmit="return false" onClick="return validateForm()">
</form>

在名称字段中输入一个空格,然后跳到下一个单元格。注意错误。您可以返回并修复,错误就会消失。单击提交后,此模式将停止!更有趣的是,它只停止/中断姓氏和电子邮件字段...

这是我的 Firefox 控制台错误:

【问题讨论】:

  • 如果您想使用脚本提交,请从不调用任何 id 或 name="submit" 开始
  • 因为提交表单会加载一个新页面。
  • 按钮上没有 onsubmit。那是在表格上。
  • 顺便说一句,传递this.id 有点傻——只传递this 这样你就不必在函数中调用getElementById
  • @mplungjan 是的,onsubmit 在这里没有做任何事情。

标签: javascript forms function validation parameters


【解决方案1】:

将表单域的ID修改为与名称和错误div前缀​​相同,这样可以避免很多错误。

我会在处理程序中传递(this),然后我可以从中获取值和 ID

按钮上没有 onsubmit。那是在表格上。

我建议您执行以下操作:

document.querySelector("[name=InviteForm]")
  .addEventListener("submit",validateForm)

使用

function validateForm(e) {
    .....  
    if (fnameErr || lnameErr || emailErr) { e.preventDefault() }
}

并将提交更改为

<input class="button submit"  type="submit" value="Get Invited">

我在这里添加了我的建议:

function validateNameField(input) {
  const inputId = input.id
  const errDivId = inputId+"Err";
  var inputValue = input.value;
  if (inputValue == "") {
    printError(errDivId, "What's your first name?");
    document.getElementById(errDivId).style.display = "none"; //could I use jQuery hide()? I don't want to report error if blank until submit (for UX)

  } else {
    var regex = /^[a-zA-Z]{2,}$/;
    if (regex.test(inputValue) === false) {
      printError(errDivId, "Valid names don't contain spaces"); //function is in formvalidation.js file
    } else {
      printError(errDivId, "");
      nameErr = false;
      document.getElementById(errDivId).style.display = "none"; //could I use jQuery hide()?
    }
  }
}

// Validate email address
function validateEmailField(input) {
  const inputId = input.id
  const errDivId = inputId+"Err";
  var inputValue = input.value;

if (inputValue == "") {
    printError(errDivId, "What's your email?");
    document.getElementById(errDivId).style.display = "none"; //could I use jQuery hide()? I don't want to report error if blank until submit (for UX)

  } else {
    // Regular expression for basic email validation
    var regex = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}/;
    if (regex.test(inputValue) === false) {
      printError(errDivId, "Valid emails don't contain any typos");
    } else {
      printError(errDivId, "");
      emailErr = false;
      document.getElementById(errDivId).style.display = "none"; //could I use jQuery hide()?
    }
  }
}

// JavaScript Document

// Defining a function to display error message
function printError(elemId, hintMsg) {
console.log(elemId)
  document.getElementById(elemId).innerHTML = hintMsg;
  document.getElementById(elemId).style.display = "block"; //could I use jQuery show()?
}

// Defining a function to validate form 
function validateForm(e) {

  // Defining error variables with a default value. True means there are errors and form won't be submitted.
  var fnameErr = lnameErr = emailErr = true;

  // Validate fname
  if (typeof document.InviteForm.fname !== "undefined") {
    var fname = document.InviteForm.fname.value;

    if (fname == "") {
      printError("fnameErr", "What's your first name?");
    } else {
      var regex = /^[a-zA-Z]{2,}$/;
      if (regex.test(fname) === false) {
        printError("fnameErr", "Valid names don't contain spaces");
      } else {
        printError("fnameErr", "");
        fnameErr = false;
        document.getElementById("fnameErr").style.display = "none"; //could I use jQuery hide()?
      }
    }
  }
  // Validate fname
  if (typeof document.InviteForm.lname !== "undefined") {
    var lname = document.InviteForm.lname.value;

    if (lname == "") {
      printError("lnameErr", "What's your last name?");
    } else {
      var regex = /^[a-zA-Z]{2,}$/;
      if (regex.test(lname) === false) {
        printError("lnameErr", "Valid names don't contain spaces");
      } else {
        printError("lnameErr", "");
        lnameErr = false;
        document.getElementById("lnameErr").style.display = "none"; //could I use jQuery hide()?

      }
    }
  }

  // Validate email address
  if (typeof document.InviteForm.email !== "undefined") {
    var email = document.InviteForm.email.value;

    if (email == "") {
      printError("emailErr", "What's your email?");
    } else {
      // Regular expression for basic email validation
      var regex = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}/;
      if (regex.test(email) === false) {
        printError("emailErr", "Valid emails don't contain any typos");
      } else {
        printError("emailErr", "");
        emailErr = false;
        document.getElementById("emailErr").style.display = "none"; //could I use jQuery hide()?
      }
    }
  }

  // Prevent the form from being submitted if there are any errors

  if (fnameErr || lnameErr || emailErr) {
    e.preventDefault(e);
  } else {
    // Creating a string from input data for preview
    var dataPreview = fname + lname + email;

    // Display input data in a dialog box before submitting the form
    alert(dataPreview);
  }
};

window.addEventListener("load",function() {
    document.querySelector("[name=InviteForm]")
      .addEventListener("submit",validateForm)
})
/* ----------> FORM <---------- */

.inviteformcontainer {
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  flex-direction: column;
  position: relative;
  height: calc(100vh - 6em);
}

.inviteform {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  width: 50vw;
  grid-column-gap: 2em;
}

.firstname {
  grid-column: 1/3;
}

.lastname {
  grid-column: 3/5;
}

.inputcontainer {}

.error {
  font-family: inherit;
  border: 1px solid #f47b22;
  background: #fafafa;
  color: #f47b22;
  font-family: sans-serif;
  font-size: .75em;
  padding: 1em 1em;
  height: 3em;
  box-sizing: border-box;
  width: 100%;
  margin-bottom: 1em;
  display: none;
}

.email {
  grid-row: 2/3;
  grid-column: 1/5;
}

.submit {
  grid-row: 3/4;
  grid-column: 2/4;
  justify-self: center;
}

.button {
  font-family: futura;
  font-size: 1em;
  font-weight: 700;
  letter-spacing: .26em;
  font-style: normal;
  text-transform: uppercase;
  color: white;
  border: 0;
  background-color: #f47b22;
  border-color: #f47b22;
  border-style: solid;
  padding: 2em 3em;
  text-align: center;
  text-decoration: none;
  cursor: pointer;
  -webkit-appearance: none;
  -moz-appearance: none;
  place-self: center;
}

.button:hover {
  background-color: #f48f22;
  border-color: #f48f22;
  border-style: solid;
  border: 0;
}

input[type=text],
input[type=number],
input[type=email] {
  font-family: inherit;
  border: 1px solid #ccc;
  background: #fafafa;
  color: #000;
  font-family: sans-serif;
  font-size: 1em;
  padding: 2em 1em;
  height: 3em;
  box-sizing: border-box;
  width: 100%;
}

input:invalid {
  box-shadow: none;
}
<form name="InviteForm" class="inviteform" method="post">
  <div class="firstname inputcontainer">
    <input type="text" id="fname" name="fname" placeholder="First Name*" required pattern="[a-zA-Z]{2,}" onfocusout="validateNameField(this)">
    <div class="error" id="fnameErr"></div>
  </div>
  <div class="lastname inputcontainer">
    <input type="text" id="lname" name="lname" placeholder="Last Name*" required pattern="[a-zA-Z]{2,}" onfocusout="validateNameField(this)">
    <div class="error" id="lnameErr"></div>
  </div>
  <div class="email inputcontainer">
    <input type="email" id="email" name="email" placeholder="Email*" required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}" onfocusout="validateEmailField(this)">
    <div class="error" id="emailErr"></div>
  </div>
  <input class="button submit" type="submit" value="Get Invited"/>
</form>

【讨论】:

  • 太棒了!谢谢。那么实际问题只是命名吗?我不认为我在任何地方都有错字......
  • 我认为这是一个组合,因为我在单击一次提交之前没有收到错误。所以也许某个地方的 ID 被覆盖了。
  • 我喜欢 const 编辑——以及一般的清理技巧!谢谢!
  • 最后,添加事件侦听器与“onclick”的原因是什么?
  • 我更新了。您的测试不是标准的,或者您通常不能执行if ((a || b || c)==true),在这种情况下您可以只使用if (a || b || c),因为它们是布尔值 - 例如测试它们是否为空白,它将是if (a==="" || b === "" ...
猜你喜欢
  • 2018-05-19
  • 1970-01-01
  • 2015-12-01
  • 2018-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-26
  • 1970-01-01
相关资源
最近更新 更多