In the examples for the jQuery Validate plugin, I see three different approaches to declaring validation rules:
<input type="text" name="whatever" class="required" />
<input type="text" name="whatever" required />
$("#myForm").validate({ rules: { whatever: "required", ... } });
But I don't see anywhere in the docs that explains why you'd use one over the other. Nor do I see an explanation of how to use the validation methods with each approach (for example, how would you use the "max( value )" method with a tag attribute or a css class?).
What are the tradeoffs between these three approaches? And how exactly do you declare all the different validation methods using each approach?
You can apply rules trough data-rule attributes. This is the easiest way and possibly the best way to maintain a clean code...
Example:
<form id="myform"> <input type="text" name="email" data-rule-required="true" data-rule-email="true"> <input type="text" name="password" id="password" data-rule-required="true" data-rule-minlength="6"> <input type="text" name="password-confirm" data-rule-required="true" data-rule-minlength="6" data-rule-equalto="#password"> </form>
You can even provide messages through data attributes:
<input id="cemail" name="email" data-rule-required="true" data-rule-email="true" data-msg-email="Please enter a valid email address" />
In JavaScript just call:
$('#myform').validate();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With