A feature that I've felt is lacking in other form-validation frameworks, is the ability to add custom constraints. Adding custom constraints in Regula is very easy. Assuming I want to add a constraint called @MustBeVivin which enforces the constraint that the value of a text field must either contain the word "Vivin" or "Awesome", I would do something like this:
jQuery(document).ready(function() { regula.custom({ name: "MustBeVivin", defaultMessage: "{label} must be equal to \"Vivin\" or \"Awesome\"", validator: function() { return this.value.toLowerCase() == "vivin" || this.value == "awesome"; } }); //Notice that custom constraints need to be defined before //you call bind() regula.bind();
Now, in HTML I can say:
Enter a name: <input type="text" id="name" name="name" class="regula-validation" data-constraints = '@MustBeVivin(label="The name"') /> Enter a word: <input type="text" id="word" name="word" class="regula-validation" data-constraints = '@MustBeVivin(label="The word"') />
When the validation runs, the fields will fail the constraint if they don't contain the word "Vivin" or "Awesome", and depending on which field failed, you will get The name must be equal to "Vivin" or "Awesome" or you'll get The word must be equal to "Vivin" or "Awesome". This is useful if you define a custom constraint that is used in many places, but you want to be able to customize the error message as well. On another note, you could also do @MustBeVivin(name="The word", message="The bird is {name}") @MustBeVivin(label="The word", message="The bird is {label}") in which case you'll get The bird is The Word. If you define a message parameter in the constraint definition, it will override the default message.
When you define custom constraints, you can also define parameters for it. For example:
jQuery(document).ready(function() { regula.custom({ name: "FooBarConstraint", defaultMessage: "{label} and {foo} and {bar}", params: ["foo", "bar"] validator: function(params) { var foo = params["foo"]; var bar = params["bar"]; /* do some validation */ return booleanResult; } }); regula.bind();
In the above example, I am defining a constraint called FooBarConstraint that accepts two parameters called foo and bar. So, in HTML you'd define it like so: @FooBarConstraint(foo="blah", bar=5). Pretty simple, right?
3 thoughts on “Regula: An annotation-based form-validator written in Javascript”