Friday, September 19, 2008

jQuery and unit testing

The following blog post of Chad Myers gives a good introduction to unit testing of jQuery client side Java Script with the aid of QUnit.

And this post of Joshua Flanagan is a follow up which explains how one could integrate the QUnit tests into a CI build.

Note: NUnit has to run on a single threaded apartment thread [STA]. To do this add an app.config to your test assembly with the following content

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="NUnit">
      <section name="TestRunner" type="System.Configuration.NameValueSectionHandler"/>
    </sectionGroup>
  </configSections>
  <NUnit>
    <TestRunner>
      <add key="ApartmentState" value="STA" />
    </TestRunner>
  </NUnit>
</configuration>

Monday, September 1, 2008

How-To add a custom validation method to the jQuery validator plug-in

For my current project I needed a custom validator method for the jQuery validator plug-in. I wanted to validate that a user has chosen a value from a combo box where the value is of type Guid.

First I implemented a JavaScript function which tests whether a given value represent a valid Guid but not an empty Guid (An empty Guid has the following form: 00000000-0000-0000-0000-000000000000). To achieve this result I use regular expressions

var isValidGuid = function(value) {
  var validGuid = /^(\{|\()?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}(\}|\))?$/;
  var emptyGuid = /^(\{|\()?0{8}-(0{4}-){3}0{12}(\}|\))?$/;
  return validGuid.test(value) && !emptyGuid.test(value);
}

The above function returns true for a valid Guid and false for every thing else.

Now I have to add this validation method to the validator plug-in as follows

$.validator.addMethod("isValidGuid", function(value, element) {
  return isValidGuid(value);
}, 'Please select a valid and non empty Guid value.');

Finally I can use this custom validation method on any form element by assigning it the class isValidGuid, e.g.

<select id="title" class="isValidGuid" title="Please select a title!">
  <option value="00000000-0000-0000-0000-000000000000" selected="selected">(select)</option>
  <option value="33a1eb15-cdbc-4c85-be01-dcb4f393c0a5">Engineer</option>
  <option value="43b5d0f7-4915-41f1-b3b9-d6335299cc22">Physicist</option>
  <option value="d80322f2-bb76-447c-a6ac-77f145bac70d">Technician</option>
</select>          

when applied we have the following outcome

image