-
Notifications
You must be signed in to change notification settings - Fork 4
New plugin
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:
- The rule name. It should match the data-rules-xxxxx attribute in the element (see below)
- 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.
- The error message.
- 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!