Validate Single Field with Hibernate Validator
Please note that the following code examples exclusively use Java’s validation API, so these examples are in no way limited to Hibernate Validator. Hibernate Validator is merely used as the implementation of the used interfaces, but other implementations can be used as well.
Validating a single field with Hibernate Validator is easy. Suppose that you have an instance of a Company class which contains validation constraints denoted by annotations, then you can do the following.
Company company = new Company();
// Set properties on company
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Company>> errors = validator.validateProperty(company, "phoneNumber");
The above obtains an instance of the Validator interface by using a factory to instantiate a concrete implementation. The validateProperty method is used to validate a particular property (in this case, phoneNumber) on an object with the value that the property has on the object. A set of ConstraintViolation objects are returned – one instance per error, or an empty set if the value did not violate any validation constraints. Of course you can then check whether or not any validation constraints were violated as such:
if (errors.isEmpty()) {
// Everything is OK!
} else {
// todo: handle errors
}
Validating an Entire Object
It is also very easy to validate all of the values of an object against the constraints on the entire object, rather than just for a specific property. This can be done as in the below example.
Company company = new Company();
// Set properties on company
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Company>> errors = validator.validate(company);
Validating Property against Dynamic Value
Another useful feature in Java’s validation API is that one can validate a given property of an object against a provided value; not the value that exists for the property on the object.
Company company = new Company();
// Set properties on company
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Company>> errors = validator.validateValue(Company.class, "phoneNumber", "12345678");
Here we validate a value that is passed as an argument rather than the value that is set for the property on the object. This is quite useful if you want to validate a given value before actually setting it on an object.