Thursday, December 18, 2008

jQuery Validation Plugin Tip: Highlight Field

The validation plugin for jQuery is a very useful plugin for validating forms before they are submitted. This tip shows you how you can highlight the field if there is an error with it.

var validator = $("#myform").validate({
 onblur: function(el)
 {
  if(validator.check(el))
   $(el).removeClass(validator.settings.errorClass);
  else
   $(el).addClass(validator.settings.errorClass);
 },
 onkeyup: function(el)
 {
  if(validator.check(el))
   $(el).removeClass(validator.settings.errorClass);
  else
   $(el).addClass(validator.settings.errorClass);
 }
});

This adds the errorClass (normally 'error') to the field being validated, which can then be styled via CSS:

input.error { border: 1px solid #c00; background: #fee }

1 comment:

Matthew said...

In case someone else comes across this, you can now achieve the same results using highlight/unhighlight options in the rules method of validate: http://docs.jquery.com/Plugins/Validation/validate#options