简体   繁体   中英

how to form validate manually in javascript

<form id="myForm"> 
  <input type="text" required />
  <button class="btn btn-primary" id="next-button"  type="submit">Next</button>
</form>

in javascript code

var nextButton = document.getElementById("next-button");
  nextButton.addEventListener("click", function(e){
    e.preventDefault();
    console.log("Next Button Clicked!");
    // Do some other work.
    form.submit();
  });

If I run this code, with text field empty, form submits which shouldn't do it. If I remove Id field in submit button, validation is working. What is my problem here? or how can I validate a form manually in javascript?

If you don't want the form to submit until you explicitly tell it to do so, replace type="submit" with type="button" in the <button> tag. The former automatically submits the form when clicked.

You can check the validity of the form the following way:

var nextButton = document.getElementById("next-button");
var form = document.getElementById("myForm");
  nextButton.addEventListener("click", function(e){
    if(form.checkValidity()) {
      e.preventDefault();
      alert("Next Button Clicked!");
      // Do some other work.
      form.submit();
    }
  });

You have a couple things going on here.

If I run this code, with text field empty, form submits which shouldn't do it. If I remove >Id field in submit button, validation is working. What is my problem here?

This is because your javascript is essentially taking over and isn't actually doing any validating. It prevents the default behavior of the button, logs a message to the console, and then submits the form.

When you remove the ID value from the button, this javascript is not running because the element ID you told it to look for doesn't exist. The reason it is validating is because now your Javascript is not taking over and the validation native to the browser is picking up on the 'required' attribute you placed in your input.

You have two paths forward, either use the native browser validation https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation

Or build your own with javascript. (There's tons of ways to do this, use google and work with a few examples you find).

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