Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
75
rated 0 times [  82] [ 7]  / answers: 1 / hits: 46943  / 12 Years ago, tue, september 18, 2012, 12:00:00

I have the following code example that works in browsers that check when they see the HTML5 required on an input like the email here:



<form id='myForm'>
<div>
<label>Email:
<input name=email type=email required title=enter your email>
</label>
<input type=submit>
</div>
</form>​


Here is a fiddle for the above.



However in my application I use a button outside of my form and the following code attached to the click event of that button:



if (!$form.valid || $form.valid()) {
$submitBt
.disableBt();
$modal
.removeBlockMessages()
.blockMessage('Contacting Server, please wait ... ', {
type: 'loading'
});
$.ajax({
url: href,
dataType: 'json',
type: 'POST',
data: $form.serializeArray()
})
.done(onDone)
.fail(onFail);
}


I have two questions here:




  • What does the following code do: (!$form.valid || $form.valid())

  • How can I check my form validity using the new HTML5 checks?


More From » jquery

 Answers
235

Assuming that you have set the form element to an object called $form, then if (!$form.valid || $form.valid()) is clever syntax that means if $form doesn't have a method called valid, or if valid() returns true. Typically you will have installed and initialized the jQuery Validation plugin by then, but this prevents the form from becoming disabled if the validation plugin is not loaded.



You can do a similar test using the HTML5 method checkValidity, looking something like this:



if (!$form.checkValidity || $form.checkValidity()) {
/* submit the form */
}


EDIT: checkValidity is a function from the HTML5 forms spec. As of February 2016 CanIUse.com reports that over 95% of browsers support it.


[#83039] Sunday, September 16, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leonardok

Total Points: 114
Total Questions: 94
Total Answers: 103

Location: France
Member since Thu, Oct 27, 2022
2 Years ago
;