简体   繁体   中英

Multi-Level Form Validation Using Javascript

I am a novice in Javascript. I just finish taking a Javascript course in Udemy. One of the Project I'm required to do is Multi-Level Form Validation Using JavaScript, but i'm having some challenges.

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. I left styles and some other stuff out.

For your convenience, I have also created a working Codepen .

Here's the 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. 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. 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. 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. When they press the next button, we validate those fields, and append p tags into the DOM if their are errors. Once they finish filling out all fields in that section, then they are free to move on.

Here is the 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')
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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