Talha5389
Talha5389

Reputation: 740

HTML5 validations with javascript

<input type="text" pattern="[a-zA-z]" required id="txtBox" />
<input type="submit" />

Upvotes: 0

Views: 93

Answers (2)

Jai
Jai

Reputation: 74738

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.');
   }
});

Upvotes: 1

Vlas Bashynskyi
Vlas Bashynskyi

Reputation: 2014

  • 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.

Upvotes: 1

Related Questions