简体   繁体   English

使用 Javascript 进行多级表单验证

[英]Multi-Level Form Validation Using Javascript

I am a novice in Javascript. I just finish taking a Javascript course in Udemy.我是Javascript的新手,刚学完Udemy的Javascript课程。 One of the Project I'm required to do is Multi-Level Form Validation Using JavaScript, but i'm having some challenges.我需要做的项目之一是使用 JavaScript 进行多级表单验证,但我遇到了一些挑战。

I have been able to get my 'Next' and 'Previous' buttons working fine.我已经能够让我的“下一个”和“上一个”按钮正常工作。 But the problem is how to display an error message if any of the input values is empty.但问题是如果任何输入值为空,如何显示错误消息。

 var next = document.getElementById('firstNext') function validate() { next.addEventListener('click', function () { let inputs = document.getElementById('fName'); let displayError = document.getElementsByClassName('error') inputs.addEventListener('input', function(e) { let inputValue = e.target.value; if (inputValue === '') { displayError.style.display = "block"; } else{ displayError.style.display = "none"; } }); }, false) } function firstNexts() { validate(); document.getElementById('first').style.display = "none"; document.getElementById('second').style.display = "block"; } function secondNext() { validate(); document.getElementById('second').style.display = "none"; document.getElementById('third').style.display = "block"; } function thirdNext() { validate(); document.getElementById('third').style.display = "none"; document.getElementById('last').style.display = "block"; } function firstPrev() { validate(); document.getElementById('second').style.display = "none"; document.getElementById('first').style.display = "block"; } function secondPrev() { validate(); document.getElementById('third').style.display = "none"; document.getElementById('second').style.display = "block"; } function lastPrev() { validate(); document.getElementById('last').style.display = "none"; document.getElementById('third').style.display = "block"; }
 .body{ background-color: #1f2833; color: white; align-content: center; } section{ height: 320px; width: 50%; margin: auto; color: white; background-color: #c6c5c7; align-content: center; }.header{ color: white; text-align: center; margin: 0px auto; padding: 10px; width: auto; } #first{ padding: 20px; border: none; border-radius: 8px; } #second, #third, #last{ display: none; align-content: center; padding: 20px; border: none; border-radius: 8px; }.top{ padding: 10px; text-align: center; }.input{ margin-top:20px; padding: 5px; width:100%; height: 30px; }.firstNext, .secondNext, .thirdNext{ float: right; margin-top: 10px; padding: 5px; background-color: #45a29e; color: #ffffff }.firstNext:hover{ background-color: red; }.firstPrev, .secondPrev, .lastPrev{ float: left; margin-top: 10px; padding: 5px; background-color: #4428e2; color: #ffffff }.firstNext:hover, .secondtNext:hover, .thirdNext:hover{ background-color: red; }.error{ font-size: 8px; color: red; margin: 0px 5px; display: none; }.input:hover, .input:active{ border: red 2px solid; }.submit{ float: right; margin-top: 10px; padding: 5px; background-color: #e22828; color: #ffffff }
 <,doctype html> <html lang="en"> <head> <.-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width: initial-scale=1"> <.-- Bootstrap CSS --> <link rel="stylesheet" type="text/css" href="style.css"> <link href="https.//cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous"> <title>Multi-step Registration Form</title> </head> <body class="body"> <div class="container"> <div class="header"> <h1>Multi-step Registration Form</h1> <h3>Pls fill in the following</h3> </div> <section> <form method="GET" onsubmit="validate()"> <fieldset id="first"> <h2 class="top">Personal Details</h2> <input type="text" name="firstName" class="input" id="fName" placeholder="First Name..."><br> <p class="error"> This field cannot be empty.</p> <input type="text" name="firstName" class="input" id="mName" placeholder="Middle Name..."><br> <p class="error"> This field cannot be empty.</p> <input type="text" name="firstName" class="input" id="lName" placeholder="Last Name..."><br> <p class="error"> This field cannot be empty.</p> <div><input type="button" name="next" value="Next" class="firstNext" id="firstNext" onclick="firstNexts()"></div> </fieldset> <fieldset id="second"> <h2 class="top">Academic Details</h2> <input type="text" name="firstName" class="input" id="fName" placeholder="First Name..."><br> <p class="error"> This field cannot be empty.</p> <input type="text" name="firstName" class="input" id="mName" placeholder="Middle Name..."><br> <p class="error"> This field cannot be empty.</p> <input type="text" name="firstName" class="input" id="lName" placeholder="Last Name..."><br> <p class="error"> This field cannot be empty.</p> <div><input type="button" name="next" value="Previous" class="firstPrev" onclick="firstPrev()"></div> <div><input type="button" name="next" value="Next" class="secondNext" onclick="secondNext()"></div> </fieldset> <fieldset id="third"> <h2 class="top">Account Details</h2> <input type="text" name="firstName" class="input" id="fName" placeholder="First Name..."><br> <p class="error"> This field cannot be empty.</p> <input type="text" name="firstName" class="input" id="mName" placeholder="Middle Name..."><br> <p class="error"> This field cannot be empty.</p> <input type="text" name="firstName" class="input" id="lName" placeholder="Last Name..."><br> <p class="error"> This field cannot be empty!</p> <div><input type="button" name="next" value="Previous" class="secondPrev" onclick="secondPrev()"></div> <div><input type="button" name="next" value="Next" class="thirdNext" onclick="thirdNext()"></div> </fieldset> <fieldset id="last"> <h2 class="top">Login Details</h2> <input type="text" name="firstName" class="input" id="fName" placeholder="First Name..."><br> <p class="error"> This field cannot be empty!</p> <input type="text" name="firstName" class="input" id="mName" placeholder="Middle Name..."><br> <p class="error"> This field cannot be empty!</p> <input type="text" name="firstName" class="input" id="lName" placeholder="Last Name..."><br> <p class="error"> This field cannot be empty!</p> <div><input type="button" name="next" value="Previous" class="lastPrev" onclick="lastPrev()"></div> <div><input type="button" name="next" value="submit" class="submit"></div> </fieldset> </form> </section> </div> </body> </div>

I do not get any errors in the console but the validation does not work.我在控制台中没有收到任何错误,但验证不起作用。 I'd really appreciate if you can help me.如果你能帮助我,我将不胜感激。 Thank you.谢谢。

Going off of what you originally had, I created something that I think might serve you better.从你最初拥有的东西出发,我创造了一些我认为可以更好地为你服务的东西。 It's a tad bit heavier on the javascript side, but simplifies the HTML. This solution is not meant to be all encompassing, but will definitely give you something to work off of.它在 javascript 方面有点重,但简化了 HTML。这个解决方案并不意味着包罗万象,但肯定会给你一些东西。 I left styles and some other stuff out.我留下了 styles 和其他一些东西。

For your convenience, I have also created a working Codepen .为了您的方便,我还创建了一个可用的Codepen

Here's the HTML:这是 HTML:

<form>
  <fieldset id="first">
    <h2 class="top">Personal Details</h2>

    <input type="text" name="firstName" class="input" id="fName" placeholder="First Name..."><br>
    <input type="text" name="firstName" class="input" id="mName" placeholder="Middle Name..."><br>
    <input type="text" name="firstName" class="input" id="lName" placeholder="Last Name..."><br>
  </fieldset>

  <fieldset id="second">
    <h2 class="top">Academic Details</h2>

    <input type="text" name="firstName" class="input" id="fName" placeholder="First Name..."><br>
    <input type="text" name="firstName" class="input" id="mName" placeholder="Middle Name..."><br>
    <input type="text" name="firstName" class="input" id="lName" placeholder="Last Name..."><br>
  </fieldset>

  <fieldset id="third">
    <h2 class="top">Account Details</h2>

    <input type="text" name="firstName" class="input" id="fName" placeholder="First Name..."><br>
    <input type="text" name="firstName" class="input" id="mName" placeholder="Middle Name..."><br>
    <input type="text" name="firstName" class="input" id="lName" placeholder="Last Name..."><br>
  </fieldset>

  <fieldset id="fourth">
    <h2 class="top">Login Details</h2>

    <input type="text" name="firstName" class="input" id="fName" placeholder="First Name..."><br>
    <input type="text" name="firstName" class="input" id="mName" placeholder="Middle Name..."><br>
    <input type="text" name="firstName" class="input" id="lName" placeholder="Last Name..."><br>
  </fieldset>

  <input id="prev-btn" type="button" value="Previous">
  <input id="next-btn" type="button" value="Next">
  <input id="submit-btn" type="submit" value="Submit">
</form>

I've removed all of the errors p tags, and removed any duplicate next and previous buttons.我删除了所有错误p标签,并删除了所有重复的下一个和上一个按钮。 You'll see at the bottom of the form, we only need one version of these buttons.您会在表单底部看到,我们只需要这些按钮的一个版本。

Now here's where things get funky, we are going to rely heavily on JavaScript here to make our life easier.现在事情变得很奇怪,我们将在这里严重依赖 JavaScript 来让我们的生活更轻松。 I could write a 100 page story about what's going on in there, but I'd prefer you just ask questions in the comments section if anything is unclear.我可以写一篇 100 页的故事来讲述里面发生的事情,但如果有任何不清楚的地方,我更希望你在评论部分提问。 From a high level perspective though, we are not allowing users to go pass the current section if they have not filled out all fields.但是,从高层次的角度来看,如果用户没有填写所有字段,我们不允许他们 go 通过当前部分。 When they press the next button, we validate those fields, and append p tags into the DOM if their are errors.当他们按下下一步按钮时,我们会验证这些字段,如果它们是错误的,我们会将 append p标记放入 DOM。 Once they finish filling out all fields in that section, then they are free to move on.一旦他们完成了该部分中的所有字段的填写,他们就可以继续前进了。

Here is the JS:这是JS:

const form = document.querySelector('form')
const nextButton = document.getElementById('next-btn')
const prevButton = document.getElementById('prev-btn')
const submitButton = document.getElementById('submit-btn')

const sections = ['first', 'second', 'third', 'fourth']
let currentSectionIdx = 0
let hasErrors = false

nextButton.onclick = (e) => {
  const currentSection = document.getElementById(sections[currentSectionIdx])
  validate(currentSection)
  
  if(hasErrors) {
    return
  }

  currentSectionIdx++
  const nextSection = document.getElementById(sections[currentSectionIdx])
  
  currentSection.style.display = 'none'
  nextSection.style.display = 'block'
  
  if(currentSectionIdx === sections.length - 1) {
    nextButton.style.display = 'none'
    submitButton.style.display = 'initial'
  } else if(currentSectionIdx === 1) {
    prevButton.style.display = 'initial'
  }
}

prevButton.onclick = (e) => {
  const currentSection = document.getElementById(sections[currentSectionIdx])
  currentSectionIdx--
  const prevSection = document.getElementById(sections[currentSectionIdx])
  
  currentSection.style.display = 'none'
  prevSection.style.display = 'block'
  
  if(currentSectionIdx === 0) {
    prevButton.style.display = 'none'
  } else if(currentSectionIdx === sections.length - 2) {
    nextButton.style.display = 'initial'
    submitButton.style.display = 'none'
  }
}

function validate(section) {
  const inputs = Array.from(section.querySelectorAll('input'))
  let errors = false
  
  for(const input of inputs) {
    const nextSibling = input.nextSibling
    
    if(nextSibling.className === 'error') {
      nextSibling.remove()
    }
  }
  
  for(const input of inputs) {
    if(input.value.trim() === '') {
      errors = true
      const p = document.createElement('p')
      p.className = 'error'
      const txt = document.createTextNode('This field cannot be empty!')
      p.appendChild(txt)
      input.after(p)
    }
  }
  
  if(errors) hasErrors = true
  else hasErrors = false
}

form.onsubmit = e => {
  e.preventDefault()
  
  const currentSection = document.getElementById(sections[currentSectionIdx])
  validate(currentSection)
  
  if(hasErrors) {
    return
  }
  
  console.log('lol')
}

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

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