skip to Main Content

I have made a form as index.html. I have a from validation using JavaScript. When the submit button is clicked it must open another html page(detail.html). When I supply wrong data, it must prevent the opening of detail.html page and display the error messages but neither of them happens .enter image description here

here is the code

<form action="/detail" method="POST" role="form" name="index" onsubmit="return validateForm()" enctype="application/x-www-form-urlencoded">
    <label for="name">Name</label>
    <input type="text" name="name" placeholder="Enter your name" required/>
    <span class="formerror"></span>
    <br />
    <label for="phone_number">Mobile:</label>
    <input type="number" name="phone_number" placeholder="enter your mobile number" required >
    <span class="formerror"></span>
    <br/>
    <label for="password">Password:</label>
    <input type="password" name="password" placeholder="enter your password" required  />
    <span class="formerror"></span>
    <br />
    <button id="btnsubmit" class="btn" onclick="submit">Submit</button>

code for form validation

<script>
    function clearErrors(){
        errors=document.getElementsByClassname('formerror');
        for(let item of errors){
            item.innerHTML="";
        }
    }
    function seterror(id,error){
        //sets error inside tag of id
        element=document.getElementById(id);
        element.getElementsByClassName('formerror')[0].innerHTML=error;
    }
    function validateForm(){
        var returnval = true;
        //performs validation and if validation fails, set the value of returnval to false.
        var name = document.forms['index']["name"].value;
        if(name.length<3)
        {
            seterror("name","length of name of too short");
            returnval=false;
        }
        var phone_number = document.forms['index']["phone_number"].value;
        if(phone_number.length!=10)
        {
            seterror("phone_number","phone number should be of 10 digits");
            returnval=false;
        }
        var password = document.forms['index']["password"].value;
        if(password.length<4)
        {
            seterror("password","password should be at least of 4 characters");
            returnval=false;
        }
        return returnval;
    }
</script>

I wanted the index.html to display the error messages when wrong data is fed to the input fields, but nothing of those happens instead detail.html page opens. detail.html must only open when correct input is given.

2

Answers


  1. You can make your code easier to overview if you get rid of the validate function and use event listeners instead.

    The invalid event listener will fire when the form is submitted and one or more input elements are not validating. I added attributes on each input element to validate against (like minlength="3" for the name and pattern="[0-9]{10}" for the telephone number). If an input element is not valid I set the invalid className. And that results in the form error text to show.

    When starting to type in an input the input event is fired, and the className is removed again.

    // this first event listener is only for testing
    // remove it to continue the POST request to /detail
    document.forms.index.addEventListener('submit', e => {
      e.preventDefault();
      console.log('Submitting the form!');
    });
    
    document.forms.index.addEventListener('invalid', e => {
      e.preventDefault();
      e.target.classList.add('invalid');
    }, true);
    
    document.forms.index.addEventListener('input', e => {
      e.preventDefault();
      e.target.classList.remove('invalid');
    });
    span.formerror {
      display: none;
    }
    
    input.invalid ~ span.formerror {
      display: inline;
    }
    <form action="/detail" method="POST" role="form" name="index" enctype="application/x-www-form-urlencoded">
      <label for="name">Name</label>
      <input type="text" name="name" minlength="3" placeholder="Enter your name" required>
      <span class="formerror">length of name of too short</span>
      <br />
      <label for="phone_number">Mobile:</label>
      <input type="tel" name="phone_number" pattern="[0-9]{10}" placeholder="enter your mobile number" required>
      <span class="formerror">phone number should be of 10 digits</span>
      <br/>
      <label for="password">Password:</label>
      <input type="password" name="password" minlength="3" placeholder="enter your password" required >
      <span class="formerror">password should be at least of 4 characters</span>
      <br />
      <button class="btn">Submit</button>
    </form>
    Login or Signup to reply.
  2. I changed your validation to use a sibling error message selected by a class selector, added some classes and CSS for that. Not perfect but shows how. Here I used the change event to clear the error.

    Note I also added some validation attributes like minlength etc.

    Many areas can be improved and made more robust here.

    function getNextSibling(elem, selector) {
      //next sibling element
      let sibling = elem.nextElementSibling;
      //No selector, return the first sibling
      if (!selector) return sibling;
      // Sibling matches selector, use it; no? next sibling and continue loop
      while (sibling) {
        if (sibling.matches(selector)) {
          return sibling;
        }
        sibling = sibling.nextElementSibling;
      }
    };
    
    function clearErrors() {
      let errors = document.getElementsByClassname('formerror');
      for (let item of errors) {
        item.textContent = "";
      }
    }
    
    function seterror(element, error) {
      let errSib = getNextSibling(element, '.formerror');
      errSib.textContent = error;
    }
    
    function validateForm(event) {
      event.preventDefault();
      let returnval = true;
      //performs validation and if validation fails, set the value of returnval to false.
      let field = document.forms['index']["name"];
      let name = field.value;
      if (name.length < 3) {
        seterror(field, "Length of name of too short");
        returnval = false;
      } else {
        seterror(field, "");
      }
      field = document.forms['index']["phone_number"];
      let phone_number = field.value;
      if (phone_number.length != 10) {
        seterror(field, "Phone number should be of 10 digits");
        returnval = false;
      } else {
        seterror(field, "");
      }
      field = document.forms['index']["password"];
      let password = document.forms['index']["password"].value;
      if (password.length < 4) {
        seterror(field, "Password should be at least of 4 characters");
        returnval = false;
      } else {
        seterror(field, "");
      }
      return returnval;
    }
    
    document.forms.index.addEventListener('submit', e => {
      e.preventDefault();
      const isValid = validateForm(e);
      console.log('Submitting the form!', isValid);
      //note how this only fires when you have all validation pass
      // check here for an entirely valid form and then submit
      // left this as something yet to be done. (check for any non-value fields; several ways to do this.
    });
    
    document.forms.index.addEventListener('invalid', e => {
      e.preventDefault();
      e.target.classList.add('invalid');
      validateForm(e);
    }, true);
    
    document.forms.index.addEventListener('change', e => {
      e.preventDefault();
      e.target.classList.remove('invalid');
      validateForm(e);
    });
    form {
      line-height: 2em;
    }
    
    .invalid {
      border: solid red 1px;
    }
    
    .formerror {
      border: solid red 1px;
      color: red;
      padding: 0.25em;
    }
    
    .formerror:empty {
      border: solid blue 1px;
      padding: 0em;
    }
    <form action="/detail" method="POST" role="form" name="index" enctype="application/x-www-form-urlencoded">
      <label for="name">Name</label>
      <input type="text" name="name" placeholder="Enter your name" required minlength="3" />
      <span class="formerror"></span>
      <br />
      <label for="phone_number">Mobile:</label>
      <input type="number" name="phone_number" placeholder="enter your mobile number" required minlength="10" maxlength="10">
      <span class="formerror"></span>
      <br/>
      <label for="password">Password:</label>
      <input type="password" name="password" placeholder="enter your password" required minlength="4" />
      <span class="formerror"></span>
      <br />
      <button id="btnsubmit" class="btn" type="submit">Submit</button>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search