文档
简单使用
首先,在pojo添加注解,hibernate-validator提供了很多内置的注解
public class Car {
@NotNull
private String manufacturer;
@NotNull
@Size(min = 2, max = 14)
private String licensePlate;
@Min(2)
private int seatCount;
public Car(String manufacturer, String licencePlate, int seatCount) {
this.manufacturer = manufacturer;
this.licensePlate = licencePlate;
this.seatCount = seatCount;
}
//getters and setters ...
}
制定message(el表达式)
@Size(
min = 2,
max = 14,
message = "The license plate '${validatedValue}' must be between {min} and {max} characters long"
)
spring集成
@Valid
最常见的使用方式是在controller层的bean前和@Valid注解配合使用
/**
* 创建新的用户
*/
@POST
@CacheEvict(key = "#user.username")
public Response createUser(@Valid @UniqueAccount Account user) {
return CommonResponse.op(() -> service.createAccount(user));
}
编码暴露
public static <T> String validate(T bean) {
Validator validator = Validation.byProvider(HibernateValidator.class)
.configure()
// .addProperty( "hibernate.validator.fail_fast", "true" )
.buildValidatorFactory().getValidator();
Set<ConstraintViolation<T>> validate = validator.validate(bean);
List<String> listError = new ArrayList<>();
if (validate.size() > 0) {
validate.forEach(tConstraintViolation -> listError.add(tConstraintViolation.getMessage()));
return StringUtils.join(listError, ",");
}
return StringUtils.EMPTY;
}
自定义校验器
@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE, TYPE_USE })
@Retention(RUNTIME)
@Constraint(validatedBy = CheckCaseValidator.class)
@Documented
@Repeatable(List.class)
public @interface CheckCase {
String message() default "{org.hibernate.validator.referenceguide.chapter06.CheckCase." +
"message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
CaseMode value();
@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Documented
@interface List {
CheckCase[] value();
}
}
定义约束器
public class CheckCaseValidator implements ConstraintValidator<CheckCase, String> {
private CaseMode caseMode;
@Override
public void initialize(CheckCase constraintAnnotation) {
this.caseMode = constraintAnnotation.value();
}
@Override
public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
if ( object == null ) {
return true;
}
if ( caseMode == CaseMode.UPPER ) {
return object.equals( object.toUpperCase() );
}
else {
return object.equals( object.toLowerCase() );
}
}
}
在field添加注解
@NotNull
@Size(min = 2, max = 14)
@CheckCase(CaseMode.UPPER)
private String licensePlate;
|