Reputation: 740
<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?
Upvotes: 0
Views: 93
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
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