jQuery Validator: Build Rules and Messages Dynamically

Ok so here’s your typical code for the jQuery Validator:

  jQuery(ELEMENT_FORM).validate({
    errorLabelContainer: ELEMENT_ERROR_DIV,
    wrapper: 'div',
    rules: {
      textboxEmailAddress: {
        required: true,
        email: true
      }
    },
    messages: {
      textboxEmailAddress: {
        required: ERROR_EMAIL_ADDRESS_REQUIRED
      }
    },
    ....

As you can see, the elements like “textboxEmailAddress” are hard coded in there which means if that name changes in the markup, this breaks. So the question is: How do I script the rules and messages so that I don’t have to hard code the element names?

Sorry was just waiting for you to finish you question. Ok, here’s the answer and it has to do with how great Javascript is as a language. (And oddly enough a trick I got from Python)

  var validationRules = new Object();
  validationRules[ELEMENT_TEXTBOX_EMAIL] = {required:true};

  var validationMessages = new Object();
  validationMessages[ELEMENT_TEXTBOX_EMAIL] = {required:ERROR_EMAIL_REQUIRED};

  jQuery(ELEMENT_FORM).validate({
            errorLabelContainer: ELEMENT_ERROR_DIV,
            wrapper: 'div',
            rules: validationRules,
            messages: validationMessages,
            ....

Where ELEMENT_TEXTBOX_EMAIL is a constant somewhere. How does this work? Well because the way dynamic languages like Javascript and Python work, objects can be treated like dictionaries which means you can add properties to them the way you would add a record to a dictionary:

  someObject['somePropertyName'] = 'hi';

is just like:

  someObject.somePropertyName = 'hi';

In fact I’m pretty sure the new Dynamic keyword in C# works in the same manor.

Now you could be a annoying and point out that replacing textboxEmailAddress with ELEMENT_TEXTBOX_EMAIL is still hard coding, and I would agree… to a point. The constant does two things:

1) Removes a “magic string” from your code.

2) Makes it really easy to update that string if the element name/id is changed in the HTML. Having only to look at one place to replace is a lot easier than 1+ places.

So there, smarty pants. What you gots to say now?