为什么我的JavaScript表单验证无效?

时间:2019-07-28 22:17:53

标签: javascript jquery

我的JS表单验证未打印出错误消息,好像它忽略了prevent默认值。

我已经多次检查了代码,但似乎找不到错误。

HTML:

<form id="form">
  <div>
    <label for="firstname">First Name</label>
    <input id="firstname" name="firstname" type="text" />

    <label for="lastname">Last Name</label>
    <input type="text" name="lastname" id="lastname" placeholder="Doe" />

    <label for="email">Email</label>
    <input type="email" name="email" id="email" placeholder="john@doe.com" />

    <label for="comment">Comment:</label>
    <textarea id="comment" name="comment" placeholder="Write something.." style="height:200px;  width: 100%"></textarea>

    <button type="submit">Submit</button>
  </div>
</form>

Javascript:

const firstname = document.getElementById("firstname")
const lastname = document.getElementById("lastname")
const email = document.getElementById("email")
const comment = document.getElementById("comment")
const form = document.getElementById('form')
const errorElement = document.getElementById('error')
form.addEventListener('submit', (e) => {
  let messages = []
  if (firstname.value === '' || firstname.value == null) {
    messages.push('Name is required')
  }
  if (messages.length > 0) {
    e.preventDefualt()
    errorElement.innerText = messages.join(', ')
  }
})

没有错误消息,但我希望它显示我在表单上方设置的js错误消息。

1 个答案:

答案 0 :(得分:0)

这是一个错字错误,请设置e.preventDefault()而不是e.preventDef ual t() 您也错过了错误div以显示错误,请参见以下代码段:

const firstname = document.getElementById("firstname")
const lastname = document.getElementById("lastname")
const email = document.getElementById("email")
const comment = document.getElementById("comment")
const form = document.getElementById('form')
const errorElement = document.getElementById('error')
form.addEventListener('submit', (e) => {
  let messages = []
  if (firstname.value === '' || firstname.value == null) {
    messages.push('Name is required')
  }
  if (messages.length > 0) {
    e.preventDefault()
    errorElement.innerText = messages.join(', ')
  }
})
<form id="form">
  <div>
    <label for="firstname">First Name</label>
    <input id="firstname" name="firstname" type="text" />

    <label for="lastname">Last Name</label>
    <input type="text" name="lastname" id="lastname" placeholder="Doe" />

    <label for="email">Email</label>
    <input type="email" name="email" id="email" placeholder="john@doe.com" />

    <label for="comment">Comment:</label>
    <textarea id="comment" name="comment" placeholder="Write something.." style="height:40px;  width: 100%"></textarea>


    <button type="submit">Submit</button>
  </div>
</form>
<div id="error"></div>