简介:
spring vallidator:是在spring context下,在spring boot项目中。我们引入spring boot-strarter-web, spring validation是对vallidator二次封装。使我们可以更加方便的springmvc中进行自动校验。
Hibernate Validator:是JSR-303参考实现。
- 常用注解:
Constranit | desc |
---|---|
@Null | 被注解的元索必须为空 |
@notNull | 被注解的元素必须不为空 |
@Min | 被注解的元素必须是数字且必须小于等于指定值 |
@Max | 被注解的元素必须是数字且必须大于等于指定值 |
@Past | 被注解的元索必须是- -个过去的日期 |
@Future | 被注解的元素必须是一个将来的日期 |
@Pattern | 被注解的元素必须符合给定的正则表达式 |
@AssertTure | 被注解的元素必须为ture |
@AssertFalse | 被注解的元素必须为false |
- 附加注解:
Constranit | desc |
---|---|
被注解的元素必须是email地址 | |
@Length | 被注解的元素必须在指定的范围内 |
@NotEmpty | 被注解的元素是必须 |
@Range | 被注解的元素可以是数字或者是数字的字符串必须在指定的范围内 |
@URL | 被注解的元素必须是一个URL |
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
自定义手机号参数校验
注解类
package com.etc.validation;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
/**
* @Author Mr.findelist
* @program: seckillplus
* @Date 2020/7/22 21:15
**/
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {IsPhoneValidation.class})
public @interface IsPhone {
String massage() default "手机号格式错误";
Class<?>[] group() default {};
Class<? extends Payload>[] payload() default {};
}
package com.etc.validation;
import com.etc.utils.IphoneValidationUtil;
import org.springframework.util.StringUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* @Author Mr.findelist
* @program: seckillplus
* 泛型第一个自定义注解
* 泛型第er个 校验参数的类型这里是手机号所以是 string
* @Date 2020/7/22 21:23
**/
public class IsPhoneValidation implements ConstraintValidator<IsPhone, String> {
@Override
public void initialize(IsPhone constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
if (StringUtils.isEmpty(value)) {
return false;
} else {
return IphoneValidationUtil.isPhone(value);
}
}
}
package com.etc.utils;
import org.springframework.util.StringUtils;
import java.util.regex.Pattern;
/**
* @Author Mr.findelist
* @program: seckillplus
* @Date 2020/7/22 21:36
* 雁阵手机号
**/
public class IphoneValidationUtil {
private static final Pattern PATTERN=Pattern.compile( "^1[345678]\\d{9}$");
/**
* 验证手机号
*/
public static boolean isPhone(String iphone){
if (StringUtils.isEmpty(iphone)) {
return false;
} else {
return PATTERN.matcher(iphone).matches();
}
}
}