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);
}
}