public enum ValidatorUtil {
instance;
public static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
public void valid(Object o, Class group) throws IllegalArgumentException {
Set<ConstraintViolation<Object>> validate = validator.validate(o, group);
if (validate.size() > 0) {
String msg = msgPrettyFormat(validate);
throw new IllegalArgumentException(msg);
}
}
public void valid(Object o) throws IllegalArgumentException {
Set<ConstraintViolation<Object>> validate = validator.validate(o);
if (validate.size() > 0) {
String msg = msgPrettyFormat(validate);
throw new IllegalArgumentException(msg);
}
}
private String msgPrettyFormat(Set<ConstraintViolation<Object>> validate) {
StringBuilder stringBuilder = new StringBuilder();
for (ConstraintViolation<Object> constraintViolation : validate) {
stringBuilder
.append("[")
.append(constraintViolation.getPropertyPath())
.append("=")
.append(constraintViolation.getInvalidValue())
.append(" -> ")
.append(constraintViolation.getMessage())
.append("] ");
}
return stringBuilder.toString();
}
}
网友评论