注解
java
package com.XX.assess.annotation;
import com.XX.assess.util.MobileValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
/**
* 手机号校验注解
* @author super
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Documented
// 校验规则
@Constraint(validatedBy = MobileValidator.class)
public @interface Mobile {
boolean required() default true;
//信息,抛出的是BindException,前端页面接收的话,我们要进行异常的捕获
String message() default "手机号码格式错误";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
校验规则
java
package com.XX.assess.util;
import cn.hutool.core.util.StrUtil;
import com.XX.assess.annotation.Mobile;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* 自定义校验规则
* @author super
*/
public class MobileValidator implements ConstraintValidator<Mobile,String> {
/**
* 是否必填,默认不必填
*/
private boolean required = false;
/**
* 初始化,获取是否必填
* @param constraintAnnotation
*/
@Override
public void initialize(Mobile constraintAnnotation) {
required = constraintAnnotation.required();
}
/**
* 判断是否校验手机号
* @param value
* @param context
* @return
*/
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
// 必填,则去校验手机号格式
if (required){
return ValidatorUtil.Mobile(value);
}else {
// 如果不必填,手机号为空,返回ture
if (StrUtil.isEmpty(value)){
return true;
}else {
// 否则校验手机号格式
return ValidatorUtil.Mobile(value);
}
}
}
}
校验方法
java
package com.XX.assess.util;
import cn.hutool.core.util.StrUtil;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author 校验工具类
*/
public class ValidatorUtil {
private static final Pattern mobile_pattern = Pattern.compile("[1]([3-9])[0-9]{9}$");
public static boolean Mobile(String mobile) {
if (StrUtil.isEmpty(mobile)){
return false;
}
Matcher matcher = mobile_pattern.matcher(mobile);
return matcher.matches();
}
}