<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>2.1.6.RELEASE</version>
</dependency>
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {IsMobileValidator.class})
public @interface IsMobile {
String message() default "手机号码格式错误";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
步骤就是讲class替换成 @interface.然后将其他的复制出来就行,message() default 需要自己写
public class IsMobileValidator implements ConstraintValidator<IsMobile,String> {
public static final String REGEX_MOBILE = "^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
@Override
public void initialize(IsMobile constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
try {
if(StringUtils.isEmpty(value))
{
return false;
}
return Pattern.matches(REGEX_MOBILE,value);
} catch (Exception e) {
return false;
}
}
}
在isValid下写判断逻辑
最后就可以使用@isMobile
@IsMobile
private String phone;