JValidations - Java validation API
JValidations is a framework to express and exercise validation rules for java objects. Its defining characteristics are:
- validation is performed by the objects themselves, not in external "validator" classes, preserving encapsulation
- validation rules are expressed in declarative java using Hamcrest matchers, not in XML or annotations or what have you
- how a validation failure is handled is entirely up to the caller through the use of callback interfaces
- extensible in that custom validations can be coded, and the DSL syntax can be modified to suit your needs
A full explanation of how to use JValidations is given in the tutorial and cookbook documents, accessible from the menu to the left. However, a simple piece of code here should give you an idea:
public class Customer implements Validatable<ValidationReport>{
private String name;
private String email;
public void buildValidation(ValidationSyntax validates, ValidationReport report) {
validates.that("name", not(isEmptyString()), _else(report,"isBlank", fieldName()));
validates.that("email", not(isEmptyString()), _else(report,"isBlank", fieldName()));
}
public interface ValidationReport {
void isBlank(String fieldName);
}
}
Here you can see that the domain object Customer defines its own validation rules. It also defines its own callback interface (ValidationReport), which the caller will have to implement in its own way.
A Customer instance can be validated like this. First define what the caller wants to do in the event of a validation failure:
public static class PrintingValidationReport implements Customer.ValidationReport {
public void isBlank(String fieldName){
System.out.println(fieldName + " is blank");
}
}
And now do the validation:
JValidations.validate(new Customer(), new PrintingValidationReport());