41 lines
1.1 KiB
Java
41 lines
1.1 KiB
Java
package eu.eudat.commons.validation;
|
|
|
|
import jakarta.validation.ConstraintValidator;
|
|
import jakarta.validation.ConstraintValidatorContext;
|
|
import org.apache.commons.beanutils.PropertyUtils;
|
|
|
|
|
|
public class RequiredOneFieldValidator implements ConstraintValidator<RequiredOneField, Object> {
|
|
|
|
private String[] fieldNames;
|
|
|
|
public void initialize(RequiredOneField constraintAnnotation) {
|
|
this.fieldNames = constraintAnnotation.fieldNames();
|
|
}
|
|
|
|
public boolean isValid(Object object, ConstraintValidatorContext constraintContext) {
|
|
|
|
if (object == null) {
|
|
return true;
|
|
}
|
|
int requiredCount = 0;
|
|
try {
|
|
for (String fieldName:fieldNames){
|
|
|
|
Object property = PropertyUtils.getProperty(object, fieldName);
|
|
if (property != null) {
|
|
requiredCount = requiredCount + 1;
|
|
}
|
|
}
|
|
if (requiredCount == 1){
|
|
return true;
|
|
}
|
|
return false;
|
|
} catch (Exception e) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
}
|
|
|