Saturday, June 1, 2013

Error handling in jQuery Validation Plugin

Regarding the error handling in jQuery validation plugin, it could be split to the following types of handling.
1. error styleClass
    - highlight the error element
2. error placement
    - field level - placing the error message together with the error element. - errorPlacement
    - form level - placing the error message in screen header or footer. - errorContainer

Now let's go through each of the handling.

1. error styleClass

define the following styleClass,
input.error { background: #FFD2D2; color:#000000; border: 1px solid red; }
and it will produce the following output
error styled input

2. error placement

a) field level
    this is the default error placement for jQuery validation plugin by inset the error message after the error element.
    but it's still allowed us to change the error placement with the errorPlacement option.
errorPlacement: function(error, element) { 
  error.appendTo( element.parent("td").next("td") );
}
OR
errorPlacement: function(error, element) {
  error.insertAfter("#elementName");
}

b) form level
the form level error message can be handled with the errorContainer option.
with the errorContainer option configured, the error messages from jQuery validation plugin will be put inside our defined error container.

i) first define a div as a error container
<div id="myErrorContainer">
    <ul />
</div>

ii) append the errorContainer option into the jQuery validation script
errorContainer: $('#myErrorContainer'),
errorLabelContainer: $('#myErrorContainer ul'),
wrapper: 'li'

source code of the page:
ggg<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
  <script>
  $(document).ready(function(){
    $("#myform").validate({
  rules: {
    field: {
      required: true,
      creditcard: true
    }
  },
    messages: {
     field: {
      required: "Required field"
       }
  },
  errorContainer: $('#myErrorContainer'),
  errorLabelContainer: $('#myErrorContainer ul'),
  wrapper: 'li'
});
  });
  </script>
  <style>
    input.error, textarea.error { background: #FFD2D2; color:#000000; border: 1px solid red; }
</style>
</head>
<body>
<form id="myform">
<div id="myErrorContainer">
    <ul />
</div>
  <label for="field">Required, creditcard (try 446-667-651): </label>
  <input class="left" id="field" name="field" />
  <br/>
  <input type="submit" value="Validate!" />
</form>
</body>
</html>



Done!!

No comments:

Post a Comment

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...