Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring jQuery Validate plugin rules -- attribute vs. class vs. code

In the examples for the jQuery Validate plugin, I see three different approaches to declaring validation rules:

  • CSS Classes -- e.g. <input type="text" name="whatever" class="required" />
  • Attributes -- e.g. <input type="text" name="whatever" required />
  • JS code -- e.g. $("#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?

like image 410
Jordan Lev Avatar asked Dec 06 '12 00:12

Jordan Lev


1 Answers

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(); 
like image 62
Primoz Rome Avatar answered Nov 13 '22 05:11

Primoz Rome