Tutorial :Simplest JQuery validation rules example



Question:

The following HTML form successfully utilizes jQuery's form validation, displaying "This field is required" to the right of the form field if left blank, and "Please enter at least 2 characters" if fewer than 2 characters were entered. However, instead of the validation metadata being specified using the class and minlength attributes on the "cname" form input field, I'd like to use jQuery's "rules" API instead, where the rules are specified in the body of the validate function. Thanks in advance:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"                       "http://www.w3.org/TR/html4/loose.dtd">  <html>  <head>    <script src="/lib/js/jquery.js"></script>    <script src="/lib/js/jquery.validate.js"></script>    <script>    $(document).ready(function(){$("#commentForm").validate(      /*       rules/messages here      */      );}      );    </script>  </head>  <body>     <form id="commentForm" method="get" action="">   <fieldset>     <legend>A simple comment form with submit validation and default messages</legend>     <p>       <label for="cname">Name</label>       <em>*</em><input id="cname" name="name" size="25" class="required" minlength="2" />     </p>     <p>       <input class="submit" type="submit" value="Submit"/>     </p>   </fieldset>   </form>  </body>  </html>  


Solution:1

rules: {      cname: {          required: true,          minlength: 2      }  },  messages: {      cname: {          required: "<li>Please enter a name.</li>",          minlength: "<li>Your name is not long enough.</li>"      }  }  


Solution:2

The examples contained in this blog post do the trick.


Solution:3

$("#commentForm").validate({      rules: {       cname : { required : true, minlength: 2 }      }  });  

Should be something like that, I've just typed this up in the editor here so might be a syntax error or two, but you should be able to follow the pattern and the documentation


Solution:4

The input in the markup is missing "type", the input (text I assume) has the attribute name="name" and ID="cname", the provided code by Ayo calls the input named "cname"* where it should be "name".


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »