I am trying to understand the purpose of Java's ConstraintValidator
interface.
It's an interface, however how does it make coding more quick or more efficient? Trying to understand benefits of using it with our team.
From Baeldung's Spring MVC Custom Validation:
The validation class implements the ConstraintValidator interface, and must also implement the isValid method; it's in this method that we defined our validation rules.
Naturally, we're going with a simple validation rule here in order to show how the validator works.
ConstraintValidator defines the logic to validate a given constraint for a given object. Implementations must comply with the following restrictions:
Code Example:
public class ContactNumberValidator implements
ConstraintValidator<ContactNumberConstraint, String> {
@Override
public void initialize(ContactNumberConstraint contactNumber) {
}
@Override
public boolean isValid(String contactField,
ConstraintValidatorContext cxt) {
return contactField != null && contactField.matches("[0-9]+")
&& (contactField.length() > 8) && (contactField.length() < 14);
}
}
The purpose is to define custom validation-logic for a custom annotation.
ConstraintValidator
In the given example the ConstraintValidator
implementation can be used as annotation on your property (assuming ContactNumberConstraint
is a public @interface
, defined as annotation for fields):
@ContactNumberConstraint
String contactField;
As such shorthand it combines several validations like otherwise have to be listed separately:
@NotNull // contactField != null
@Pattern(regexp="[0-9]+" ) // contactField.matches("[0-9]+")
@Length(min=9, max=13) // (contactField.length() > 8) && (contactField.length() < 14)
String contactField;
Here the implemented ConstraintValidator
is used to validate the property, for example if used as parameter (in a REST-controller, or any other validated method).
With this pair of annotation and validator you can simply declare a rather complex validation at any field or class by just annotating the field - by adding one line. Spring would care about initiating the validation. It executes the logic defined in validator and handles errors.
This predefined validation component as pair of annotation-interface and validator can be reused easily at many places (reduce code duplication), it can be composed and allows giving complex validations a name (using an expressive annotation name). Through its declarative way (annotation) it is loosely coupled.
More on benefits of Java Bean Validation (JSR 303, 380)