Monday, September 15, 2008

jQuery Validation and default messages

Here is how we specify errors messages for the jQuery Validation plugin by Jörn Zaefferer: For built-in validators we modify $.validator.messages, as Jörn shows here.
$.extend($.validator.messages, {
  required: "Required",
  email: "Email not valid",
  ...
});
(we fill the actual messages in server-side processing, we don't hard-code them in the JS) For custom validators we... add custom validators.
$.validator.addMethod(
  "shouldBeGreen",
  function(value, element) {
    return this.optional(element) || /green/.test(value);
  },
  "Not green"
);
Now we can specify 'shouldBeGreen' in an input's class. That's it. Pretty simple, but it took us a while to figure it out so I hope this helps somebody.

3 comments:

  1. This method doesn't work in IE6 and 7. And also gives a nasty error.

    ReplyDelete
  2. Interesting - I use it with IE6 and IE7 (and other browsers) without any problems. What error are you getting?

    ReplyDelete
  3. Works fine for me.

    I'm willing to be you have an extra comment at the end of the object.

    email: "Email not valid",

    ReplyDelete