SpringBoot使用validator校验
创建一个demo类,说一下本文使用demo中校验使用的注解: @NotEmpty:非空 @Length:长度,最长或者最短 @Email:校验email @Pattern:使用正则校验,本文使用的是身份证的正则
public class SegmentVo {
@NotNull
@NotEmpty ( groups= { AvailableFlightGroup. class } )
private String deptCity;
@Pattern ( regexp= "[A-Z]{3}" , groups= { DestinationFlightGroup. class } )
@NotEmpty ( groups= { DestinationFlightGroup. class } )
private String arrCity;
@DateValidator ( regexp= "yyyyMMdd" , message= "日期格式不正确,正确的格式类似于19980413" )
@NotEmpty
private String deptDate;
@NotEmpty
private String arrDate;
@NotEmpty
@Email
private String email;
}
@Configuration
public class ValidatorConfig {
@Bean
public Validator validator ( ) {
ValidatorFactory validatorFactory = Validation. byProvider ( HibernateValidator. class )
. configure ( )
. addProperty ( "hibernate.validator.fail_fast" , "true" )
. buildValidatorFactory ( ) ;
return validatorFactory. getValidator ( ) ;
}
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor ( ) {
MethodValidationPostProcessor processor = new MethodValidationPostProcessor ( ) ;
processor. setValidator ( validator ( ) ) ;
return processor;
}
}