<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
如何验证呢:
第一步,加上注解@Valid
第二步,在属性上加注解
自定义校验器:
ValidatorUtil :
package com.imooc.miaosha.util; import java.util.regex.Matcher;
import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; public class ValidatorUtil { 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();
} // public static void main(String[] args) {
// System.out.println(isMobile("18912341234"));
// System.out.println(isMobile("1891234123"));
// }
}
IsMobile :
package com.imooc.miaosha.validator; import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target; import javax.validation.Constraint;
import javax.validation.Payload; @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {IsMobileValidator.class })
public @interface IsMobile { boolean required() default true; String message() default "手机号码格式错误"; Class<?>[] groups() default { }; Class<? extends Payload>[] payload() default { };
}
IsMobileValidator:
package com.imooc.miaosha.validator;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext; import org.apache.commons.lang3.StringUtils; import com.imooc.miaosha.util.ValidatorUtil; public class IsMobileValidator implements ConstraintValidator<IsMobile, String> { private boolean required = false; public void initialize(IsMobile constraintAnnotation) {
required = constraintAnnotation.required();
} public boolean isValid(String value, ConstraintValidatorContext context) {
if(required) {
return ValidatorUtil.isMobile(value);
}else {
if(StringUtils.isEmpty(value)) {
return true;
}else {
return ValidatorUtil.isMobile(value);
}
}
} }