-
Notifications
You must be signed in to change notification settings - Fork 24
Home
Notice: Regula now includes an optional jQuery plugin
Regula is an annotation-based form-validation framework that aims to make form-validation flexible, easier, and more robust. Regula is also built to be easily extensible. Regula takes its inspiration from Hibernate Bean Validation annotations and uses HTML5 custom-attributes to accomplish validation. Validation in Regula centers around constraints. A constraint defines a set of rules that the value of an input element, or the input elements of a form, must abide by.
Before talking about the constraints themselves, it will be helpful to see them in action. Using Regula is very simple. You can create your form as you normally would, but this time you add constraints on fields that require them:
<input id = "myInput"
name = "myInput"
type = "text"
data-constraints = '@NotEmpty @Numeric @Between(min=1, max=5)' />
This snippet of code defines a text-box that cannot be empty and that can only contain numeric values between 1 and 5 (both inclusive). Of course, simply adding the constraints is not enough. You actually have to start the validation and inspect the results. That is easily done in the following manner (example uses jQuery):
jQuery(document).ready(function() {
// must call regula.bind() first. The best place would be in an
// onload handler. This function looks for elements with an
// attribute called "data-constraints" and binds the
// appropriate constraints to the elements
regula.bind();
jQuery("#myForm").submit(function() {
// this function performs the actual validation
var validationResults = regula.validate();
for(var i = 0; i < validationResults.length; i++) {
var validationResult = validationResults[i];
alert(validationResult.message);
}
});
});
Don’t worry too much about the validationResults
array or the validationResult
object. That will be covered later. The above example simply demonstrates the use of the validation framework.