javax.validation.EqualsValidator Maven / Gradle / Ivy
package javax.validation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.validation.ConstraintValidatorContext.ConstraintViolationBuilder;
import javax.validation.constraints.Equals;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
public class EqualsValidator implements ConstraintValidator {
private String sourceFieldName;
private String targetFieldName;
private List fieldNames;
private String message;
@Override
public void initialize(Equals constraintAnnotation) {
this.fieldNames = Arrays.asList(constraintAnnotation.value());
this.sourceFieldName = constraintAnnotation.source();
this.targetFieldName = constraintAnnotation.target();
this.message = constraintAnnotation.message();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
boolean result = isValid(value);
if (!result) {
ConstraintViolationBuilder builder = context.buildConstraintViolationWithTemplate(this.message);
for (String fieldName : this.fieldNames) {
builder.addPropertyNode(fieldName).addConstraintViolation();
}
}
return result;
}
private boolean isValid(Object value) {
if (ObjectUtils.isEmpty(this.fieldNames)) {
return true;
}
// List