展示层
import lombok.Data;
@Data
public class UserVo {
@IsMobile
private String mobile;
}
注解类:
import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.ReportAsSingleViolation;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.lang.annotation.*;
@Documented
//校验的规则类
@Constraint(
validatedBy = {MyValidator.class}
)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@ReportAsSingleViolation
@NotNull
@Size(
min = 1
)
/**
* 自定义注解类
*/
public @interface IsMobile {
boolean mobile_status() default true;
String message() default "手机号格式错误";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
实现 ConstraintValidator
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class MyValidator implements ConstraintValidator<IsMobile,String> {
private boolean mobile_status=false;
//数据初始化
@Override
public void initialize(IsMobile isMobile) {
mobile_status = isMobile.mobile_status();
}
//手机号校验规则
@Override
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
if (mobile_status){
}else {
}
return false;
}
}