@Null 被注释的元素必须为 null
@NotNull 被注释的元素必须不为 null
@AssertTrue 被注释的元素必须为 true
@AssertFalse 被注释的元素必须为 false
@Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max=, min=) 被注释的元素的大小必须在指定的范围内
@Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
@Past 被注释的元素必须是一个过去的日期
@Future 被注释的元素必须是一个将来的日期
@Pattern(regex=,flag=) 被注释的元素必须符合指定的正则表达式
Hibernate Validator提供的校验注解:
@NotBlank(message =) 验证字符串非null,且长度必须大于0
@Email 被注释的元素必须是电子邮箱地址
@Length(min=,max=) 被注释的字符串的大小必须在指定的范围内
@NotEmpty 被注释的字符串的必须非空
@Range(min=,max=,message=) 被注释的元素必须在合适的范围内
- 编写校验注解
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {IsMobileValidator.class})
public @interface IsMobile {
String message() default "手机号码格式有问题";
boolean isRequired() default false;
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
- 编写具体的实现类
我们知道注解只是一个标记,真正的逻辑还要在特定的类中实现,上一步的注解指定了实现校验功能的类为IsMobileValidator
public class IsMobileValidator implements ConstraintValidator<IsMobile, String> {
private boolean required = false;
private static final Pattern mobile_pattern = Pattern.compile("1\\d{10}");
public static boolean isMobile(String src) {
if (StringUtils.isEmpty(src)) {
return false;
}
Matcher m = mobile_pattern.matcher(src);
return m.matches();
}
@Override
public void initialize(IsMobile constraintAnnotation) {
required = constraintAnnotation.isRequired();
}
@Override
public boolean isValid(String phone, ConstraintValidatorContext constraintValidatorContext) {
if (required) {
return isMobile(phone);
} else {
if (StringUtils.isEmpty(phone)) {
return true;
} else {
return isMobile(phone);
}
}
}
}
- 测试自定义注解的功能
@Data
public class User {
@NotNull
@Size(min=2, max=30,message = "请检查名字的长度是否有问题")
private String name;
@NotNull
@Min(18)
private Integer age;
@IsMobile
private String phone;
}