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 }

Comments

B007H 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

Popular posts from this blog

Link: HTML Agility Pack (.NET)

Basic Excel Spreadsheet Generation (ASP/ASP.NET)

ASP.NET: Binding alphabet to dropdown list