简体   繁体   中英

HTML5 validations with javascript

<input type="text" pattern="[a-zA-z]" required id="txtBox" />
<input type="submit" />
  • How do you set "required" attribute from javascript?

  • If I call a javascript event from a submit-type input, how do I check whether that submit request failed due to HTML5 validation errors?

  • Is there a way to force html validation without the submit event happening?

  • document.getElementById('txtBox').required = true;
  • document.getElementById('txtBox').validity.valid is equal to true or false depending on the validity of the element.

There is also invalid event that is fired on invalid form controls.

How do you set "required" attribute from javascript?

You can use .prop() method for this:

$('#txtBox').prop('required', true);

If I invoke a click event from javascript on "input" element of type Submit, how do I check if that submit request failed due to HTML5 validation errors?

If you have a html5 required attribute on an input element then if that is not validated properly your form will not be submitted.

Is there a way to force html to check for validations without submit event happening?

Well you can write some function for the element's value check on keyup, keydown events that would do the trick for you then.

something like:

$('#txtBox').prop('required', true);

$('#txtBox').on('keyup', function(){
  var regex = /^[a-zA-z]+$/;
   if(!regex.test(this.value)){
      alert(this.id + ' is a required field.');
   }
});

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