Skip to content
brunobg edited this page Jun 12, 2013 · 1 revision

To create a new plugin, that is, support some new kind of validation, you have to provide a callback and register it with addMethod. Let's see an example: suppose you have two date fields, and one should be after the other. Let's call it afterDate:

$.validarium.addMethod("afterDate", function(value, element, param) {
	var endDateEl = $(param);
	var startDateEl = $(element);
	if (!endDateEl || !startDateEl) {
		return true;
	}
	var endDate = Date.parse(endDateEl.val());
	var startDate = Date.parse(startDateEl.val());
	return (endDate >= startDate);
}, 'Start date must be before end date.', 'onsubmit');

So addMethod receives 4 arguments:

  1. The rule name. It should match the data-rules-xxxxx attribute in the element (see below)
  2. The callback. It receives three arguments: 2. The element value 2. The element itself 2. The value of the data-rules-xxxx attribute in the element.
  3. The error message.
  4. The event to watch, one of: 'ontype' (on every key that is pressed), 'onblur' (when the user moves the cursor out of this element), 'onsubmit' (on form submission), 'onalways' (all three).

Here's how your HTML should look:

 <p>Start date: <input name="startDate" data-rules-afterDate="input[name='endDate']"/></p>
 <p>End date: <input name="endDate"/></p>

And that's it!

Clone this wiki locally