Regula as a jQuery Plugin

Earlier this evening I came across a Stack Overflow question regarding a most excellent new javascript validation framework, called Regula. Regula is an annotation-based validation framework that hides the complexities of binding complex validation events to controls by extending the DOM element itself with annotations about how it should be validated. Here is a quick example:

1

In the above example, im forcing that textbox to validate against two constraints, a @NotEmpty constraint, and an @Email constraint, both of which are quite self-explanatory. Although I’ve only just started looking at it, it does look very promising, offering an array of built-in constraints, as well as the ability to quickly add your own, allowing you to easily reuse constraints on multiple fields across multiple pages.

One thing I quickly wanted to add in though, as a way to use Regula as a jQuery plugin, and thus I added the following to the Regula source:

01
if
(jQuery) {
02

(
function
($)
03

{
04

$.regula =
function
(formId, callback) {
05

regula.bind();
06

07

$(
“#”

  • formId).submit(
    function
    () {
    08

var
validationResults = regula.validate();
09

10

if
(validationResults.length > 0)
11

{
12

if
(callback)
13

callback(validationResults);
14

15

return
false
;
16

}
17

18

return
true
;
19

});
20

};
21

})(jQuery);
22
}
Now we can easily call:

1
$(
function
()
2
{
3

$.regula(
“myForm”
,
function
(results)
4

{
5

// Do something with validation results here.
6

});
7
});
This greatly simplifies the binding of the validation controls to the form, and gives us an optional callback for when validation fails.

Please visit Vivin Paliath’s blog for more information

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post