Skip to content

Instantly share code, notes, and snippets.

@XakepSDK
Created July 27, 2018 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XakepSDK/391783e3b79f839a93a8f45c886b38e0 to your computer and use it in GitHub Desktop.
Save XakepSDK/391783e3b79f839a93a8f45c886b38e0 to your computer and use it in GitHub Desktop.
package dk.xakeps.truestarter.server.validator;
import org.apache.commons.beanutils.PropertyUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.ValidationException;
import java.lang.reflect.InvocationTargetException;
public class CrossFieldValidator implements ConstraintValidator<CrossField, Object> {
private String[] fields;
@Override
public void initialize(CrossField constraintAnnotation) {
this.fields = constraintAnnotation.fields();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
Object prevFieldValue = null;
int i = 0;
for (String field : fields) {
try {
Object property = PropertyUtils.getProperty(value, field);
if (i == 0) {
prevFieldValue = property;
i++;
continue;
}
if (!prevFieldValue.equals(property)) {
return false;
}
prevFieldValue = property;
i++;
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new ValidationException("Failed validating bean", e);
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment