spring boot 参数校验之 validation 的介绍与使用

前言

在开发项目的时候,后台的参数校验是必不可少的,常见的校验代码如下

if (StringUtils.hasLength(user.getUsername())) {
    return BaseResult.error("用户名不能为空");
}
if (StringUtils.hasLength(user.getPassword())) {
    return BaseResult.error("密码不能为空");
}

当校验的参数过多时,这样的代码看起来就很不优雅

使用 Validation API 可以解决这个问题

Validation

spring boot 启动依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

相关注解说明

@AssertFalse

源码英文解释,按照自己的理解翻译对应中文如下

/**
 * The annotated element must be false. 被添加此注解的元素的值必须为 false
 * Supported types are {@code boolean} and {@code Boolean}. 支持的属性类型有 boolean 和 Boolean
 * <p>
 * {@code null} elements are considered valid. 属性值为 null 时被认为是有效的,与 false 等价
 *
 * @author Emmanuel Bernard
 */

使用示例

@AssertFalse(message = "status 的值不能为 true")
private Boolean status;
  • message 参数

    元素值无效时所提示的信息,不写这个参数时,有默认值

@AssertTrue

源码英文解释,按照自己的理解翻译对应中文如下

/**
 * The annotated element must be true. 被添加此注解的元素的值必须为 true
 * Supported types are {@code boolean} and {@code Boolean}. 支持的属性类型有 boolean 和 Boolean
 * <p>
 * {@code null} elements are considered valid. 属性值为 null 时被认为是有效的,与 true 等价
 *
 * @author Emmanuel Bernard
 */

使用示例

@AssertTrue(message = "status 的值不能为 false")
private Boolean status;
  • message 参数

    元素值无效时所提示的信息,不写这个参数时,有默认值

@DecimalMax

源码英文解释,按照自己的理解翻译对应中文如下

/**
 * The annotated element must be a number whose value must be lower or
 * equal to the specified maximum. 被添加此注解的元素的值必须是数字,其值必须小于等于指定的最大值
 * <p>
 * Supported types are: 支持的类型如下
 * <ul>
 *     <li>{@code BigDecimal}</li>    BigDecimal
 *     <li>{@code BigInteger}</li>    BigInteger
 *     <li>{@code CharSequence}</li>  CharSequence
 *     <li>{@code byte}, {@code short}, {@code int}, {@code long},and their respective 
 *     wrappers</li>  byte,short,int,long 以及它们各自的封装器
 * </ul>
 * Note that {@code double} and {@code float} are not supported due to rounding errors
 * (some providers might provide some approximative support). 注意,由于舍入错误,double 和 float 不受支持(一些提供程序可能提供一些近似支持)。
 * <p>
 * {@code null} elements are considered valid. 属性值为 null 时被认为是有效的
 *
 * @author Emmanuel Bernard
 */

使用示例

@DecimalMax(value = "1000", message = "age 的值必须小于等于1000")
private Integer age;
  • message 参数

    元素值无效时所提示的信息,不写这个参数时,有默认值

  • value 参数

    用来指定最大值

  • inclusive 参数

    指定指定的最大值是包含的还是不包含的。默认情况下,它是包含的。

@DecimalMin

源码英文解释,按照自己的理解翻译对应中文如下

/**
 * The annotated element must be a number whose value must be higher or
 * equal to the specified minimum. 被添加此注解的元素的值必须是数字,其值必须大于等于指定的最小值
 * <p>
 * Supported types are: 支持的类型如下
 * <ul>
 *     <li>{@code BigDecimal}</li>     BigDecimal
 *     <li>{@code BigInteger}</li>     BigInteger
 *     <li>{@code CharSequence}</li>   CharSequence
 *     <li>{@code byte}, {@code short}, {@code int}, {@code long}, and their respective
 *     wrappers</li>   byte,short,int,long 以及它们各自的封装器
 * </ul>
 * Note that {@code double} and {@code float} are not supported due to rounding errors
 * (some providers might provide some approximative support). 注意,由于舍入错误,double 和 float 不受支持(一些提供程序可能提供一些近似支持)。
 * <p>
 * {@code null} elements are considered valid. 属性值为 null 时被认为是有效的
 *
 * @author Emmanuel Bernard
 */

使用示例

@DecimalMin(value = "1000", message = "age 的值必须大于等于1000")
private Integer age;
  • message 参数

    元素值无效时所提示的信息,不写这个参数时,有默认值

  • value 参数

    用来指定最小值

  • inclusive 参数

    指定指定的最小值是包含的还是不包含的。默认情况下,它是包含的。

@Digits

源码英文解释,按照自己的理解翻译对应中文如下

/**
 * The annotated element must be a number within accepted range. 被添加此注解的元素的值必须是可接受范围之内的数字
 * <p>
 * Supported types are: 支持的类型如下
 * <ul>
 *     <li>{@code BigDecimal}</li>    BigDecimal
 *     <li>{@code BigInteger}</li>    BigInteger
 *     <li>{@code CharSequence}</li>  CharSequence
 *     <li>{@code byte}, {@code short}, {@code int}, {@code long}, and their respective
 *     wrapper types</li>   byte,short,int,long 以及它们各自的封装器
 * </ul>
 * <p>
 * {@code null} elements are considered valid. 属性值为 null 时被认为是有效的
 *
 * @author Emmanuel Bernard
 */

使用示例

@Digits(integer = 1, fraction = 2)
private BigDecimal digitsNumber;
  • integer 参数

    指定这个数可接受的最大整数位数,比如指定 1 位,整数位不能超过 1 位,例如11,这时整数位为 2位 ,超过 1 位了

  • fraction 参数

    指定这个数字接受的最大小数位数 比如指定 2,则小数位不超超过 2 位,例如 1.234,这时小数位为 3 位,超过 2 位了

  • message 参数

    元素值无效时所提示的信息,不写这个参数时,有默认值

@Email

源码英文解释,按照自己的理解翻译对应中文如下

/**
 * The string has to be a well-formed email address. Exact semantics of what makes up a valid
 * email address are left to Jakarta Bean Validation providers. Accepts {@code CharSequence}.
 * 字符串必须是格式良好的电子邮件地址。组成有效电子邮件地址的确切语义留给 Jakarta Bean Validation 提供程序。接受 CharSequence 参数。
 * <p>
 * {@code null} elements are considered valid. 属性值为 null 时被认为是有效的
 *
 * @author Emmanuel Bernard
 * @author Hardy Ferentschik
 *
 * @since 2.0
 */

使用示例

@Email(regexp = "[a-z|A-Z|0-9].*@qq\\.com", message = "请输入正确的qq邮箱")
private String email;
  • regexp 参数

    元素必须匹配的附加正则表达式。默认值是任意字符串(‘.’)

    默认的是所有通用邮箱,可以使用正则表达式自定义邮箱,比如 qq 邮箱

  • Flag 参数

    可以与 regexp 参数组合使用,用于指定正则表达式选项

  • message 参数

    元素值无效时所提示的信息,不写这个参数时,有默认值

@Future

源码英文解释,按照自己的理解翻译对应中文如下

/**
 * The annotated element must be an instant, date or time in the future.
 * 被添加此注解的元素的值必须是未来的某个时刻、日期或时间。
 * <p>
 * <i>Now</i> is defined by the {@link ClockProvider} attached to the {@link Validator} or
 * {@link ValidatorFactory}. The default {@code clockProvider} defines the current time
 * according to the virtual machine, applying the current default time zone if needed.
 * 现在,是由附加到 Validator 接口或 ValidatorFactory 接口的 ClockProvider 定义的。默认的 clockProvider 根据虚拟机定义当前时间,如果需要,应用当
 * 前默认时区。
 * <p>
 * Supported types are: 所支持的类型如下:
 * <ul>
 *     <li>{@code java.util.Date}</li>
 *     <li>{@code java.util.Calendar}</li>
 *     <li>{@code java.time.Instant}</li>
 *     <li>{@code java.time.LocalDate}</li>
 *     <li>{@code java.time.LocalDateTime}</li>
 *     <li>{@code java.time.LocalTime}</li>
 *     <li>{@code java.time.MonthDay}</li>
 *     <li>{@code java.time.OffsetDateTime}</li>
 *     <li>{@code java.time.OffsetTime}</li>
 *     <li>{@code java.time.Year}</li>
 *     <li>{@code java.time.YearMonth}</li>
 *     <li>{@code java.time.ZonedDateTime}</li>
 *     <li>{@code java.time.chrono.HijrahDate}</li>
 *     <li>{@code java.time.chrono.JapaneseDate}</li>
 *     <li>{@code java.time.chrono.MinguoDate}</li>
 *     <li>{@code java.time.chrono.ThaiBuddhistDate}</li>
 * </ul>
 * <p>
 * {@code null} elements are considered valid. 属性值为 null 时被认为是有效的
 *
 * @author Emmanuel Bernard
 */

使用示例

@Future(message = "秒杀时间必须是一个将来时间")
private Date secKillTime;
  • message 参数

    元素值无效时所提示的信息,不写这个参数时,有默认值

@FutureOrPresent

源码英文解释,按照自己的理解翻译对应中文如下

/**
 * The annotated element must be an instant, date or time in the present or in the future.
 * 被添加此注解的元素必须是当前或将来的即时、日期或时间。
 * <p>
 * <i>Now</i> is defined by the {@link ClockProvider} attached to the {@link Validator} or
 * {@link ValidatorFactory}. The default {@code clockProvider} defines the current time
 * according to the virtual machine, applying the current default time zone if needed.
 * 现在,是由附加到 Validator 接口或 ValidatorFactory 接口的 ClockProvider 定义的。默认的 clockProvider 根据虚拟机定义当前时间,如果需要,应用当
 * 前默认时区。
 * <p>
 * The notion of present here is defined relatively to the type on which the constraint is
 * used. For instance, if the constraint is on a {@link Year}, present would mean the whole
 * current year.
 * 这里的 present 概念是相对于使用约束的类型定义的。例如,如果约束是在 Year 上,present表示整个当前年份。
 * <p>
 * Supported types are: 所支持的类型如下
 * <ul>
 *     <li>{@code java.util.Date}</li>
 *     <li>{@code java.util.Calendar}</li>
 *     <li>{@code java.time.Instant}</li>
 *     <li>{@code java.time.LocalDate}</li>
 *     <li>{@code java.time.LocalDateTime}</li>
 *     <li>{@code java.time.LocalTime}</li>
 *     <li>{@code java.time.MonthDay}</li>
 *     <li>{@code java.time.OffsetDateTime}</li>
 *     <li>{@code java.time.OffsetTime}</li>
 *     <li>{@code java.time.Year}</li>
 *     <li>{@code java.time.YearMonth}</li>
 *     <li>{@code java.time.ZonedDateTime}</li>
 *     <li>{@code java.time.chrono.HijrahDate}</li>
 *     <li>{@code java.time.chrono.JapaneseDate}</li>
 *     <li>{@code java.time.chrono.MinguoDate}</li>
 *     <li>{@code java.time.chrono.ThaiBuddhistDate}</li>
 * </ul>
 * <p>
 * {@code null} elements are considered valid. 属性值为 null 时被认为是有效的
 *
 * @author Guillaume Smet
 * @since 2.0
 */

使用示例

@FutureOrPresent(message = "需要是一个将来或现在的时间")
private Date time;

message 参数

元素值无效时所提示的信息,不写这个参数时,有默认值

@Max

源码英文解释,按照自己的理解翻译对应中文如下

/**
 * The annotated element must be a number whose value must be lower or
 * equal to the specified maximum. 被添加此注解的元素的值必须是数字,其值必须小于等于指定的最大值
 * <p>
 * Supported types are: 支持的类型如下
 * <ul>
 *     <li>{@code BigDecimal}</li>  BigDecimal
 *     <li>{@code BigInteger}</li>  BigInteger
 *     <li>{@code byte}, {@code short}, {@code int}, {@code long}, and their respective
 *     wrappers</li>  byte,short,int,long 以及它们各自的封装器
 * </ul>
 * Note that {@code double} and {@code float} are not supported due to rounding errors
 * (some providers might provide some approximative support). 
 * 注意,由于舍入错误,double 和 float 不受支持(一些提供程序可能提供一些近似支持)。
 * <p>
 * {@code null} elements are considered valid. 属性值为 null 时被认为是有效的
 *
 * @author Emmanuel Bernard
 */

使用示例

@Max(value = 100,message = "超出最大值!")
private Integer maxValue;
  • message 参数

    元素值无效时所提示的信息,不写这个参数时,有默认值

  • value 参数

    用来指定最大值

@Min

源码英文解释,按照自己的理解翻译对应中文如下

/**
 * The annotated element must be a number whose value must be higher or
 * equal to the specified minimum. 添加此注解的元素的值必须是数字,其值必须大于等于指定的最小值
 * <p>
 * Supported types are: 支持的类型如下
 * <ul>
 *     <li>{@code BigDecimal}</li>  BigDecimal
 *     <li>{@code BigInteger}</li>  BigInteger
 *     <li>{@code byte}, {@code short}, {@code int}, {@code long}, and their respective
 *     wrappers</li> byte,short,int,long 以及它们各自的封装器
 * </ul>
 * Note that {@code double} and {@code float} are not supported due to rounding errors
 * (some providers might provide some approximative support).
 * <p>
 * 注意,由于舍入错误,double 和 float 不受支持(一些提供程序可能提供一些近似支持)。
 * {@code null} elements are considered valid. 属性值为 null 时被认为是有效的
 *
 * @author Emmanuel Bernard
 */

使用示例

@Min(value = 10, message = "不能小于所指定的最小值!")
private Integer minValue;
  • message 参数

    元素值无效时所提示的信息,不写这个参数时,有默认值

  • value 参数

    用来指定最小值

@Negative

源码英文解释,按照自己的理解翻译对应中文如下

/**
 * The annotated element must be a strictly negative number (i.e. 0 is considered as an
 * invalid value). 添加此注解的元素的值必须是严格的负数(即 0 被视为无效值)。
 * <p>
 * Supported types are: 支持的类型如下:
 * <ul>
 *     <li>{@code BigDecimal}</li> BigDecimal
 *     <li>{@code BigInteger}</li> BigInteger
 *     <li>{@code byte}, {@code short}, {@code int}, {@code long}, {@code float},
 *     {@code double} and their respective wrappers</li>  byte,short,int,long,floatm,double 以及它们各自的封装器
 * </ul>
 * <p>
 * {@code null} elements are considered valid. 属性值为 null 时被认为是有效的
 *
 * @author Gunnar Morling
 * @since 2.0
 */

使用示例

@Negative(message = "元素值必须为负数")
private Integer negativeValue;
  • message 参数

    元素值无效时所提示的信息,不写这个参数时,有默认值

@NegativeOrZero

源码英文解释,按照自己的理解翻译对应中文如下

/**
 * The annotated element must be a negative number or 0. 添加此注解的元素的值必须是负数或0
 * <p>
 * Supported types are:  支持的类型如下:
 * <ul>
 *     <li>{@code BigDecimal}</li> BigDecimal
 *     <li>{@code BigInteger}</li> BigInteger
 *     <li>{@code byte}, {@code short}, {@code int}, {@code long}, {@code float},
 *     {@code double} and their respective wrappers</li> byte,short,int,long,floatm,ouble 以及它们各自的封装器
 * </ul>
 * <p>
 * {@code null} elements are considered valid. 属性值为 null 时被认为是有效的
 *
 * @author Gunnar Morling
 * @since 2.0
 */

使用示例

@NegativeOrZero(message = "元素值必须为负数或0")
private Integer negativeOrZeroValue;
  • message 参数

    元素值无效时所提示的信息,不写这个参数时,有默认值

@NotBlank

源码英文解释,按照自己的理解翻译对应中文如下

/**
 * The annotated element must not be {@code null} and must contain at least one 添加此注解的元素的值不能为 null 并且必须至少包含长度为 1 
 * 的字符串
 * non-whitespace character. Accepts {@code CharSequence}. 非空白字符。接受 CharSequence 接口
 *
 * @author Hardy Ferentschik
 * @since 2.0
 *
 * @see Character#isWhitespace(char)
 */

使用示例

@NotBlank(message = "值不能为 null 且长度大于等于1")
private String password;
  • message 参数

    元素值无效时所提示的信息,不写这个参数时,有默认值

@NotEmpty

源码英文解释,按照自己的理解翻译对应中文如下

/**
 * The annotated element must not be {@code null} nor empty.  添加此注解的元素的值不能为 null 或为空。
 * <p>
 * Supported types are: 支持的类型如下:
 * <ul>
 * <li>{@code CharSequence} (length of character sequence is evaluated)</li> CharSequence
 * <li>{@code Collection} (collection size is evaluated)</li> Collection
 * <li>{@code Map} (map size is evaluated)</li> Map
 * <li>Array (array length is evaluated)</li> Array 数组长度的计算
 * </ul>
 *
 * @author Emmanuel Bernard
 * @author Hardy Ferentschik
 *
 * @since 2.0
 */

使用示例

@NotEmpty(message = "值不能为 null 或为空")
private String password;
  • message 参数

    元素值无效时所提示的信息,不写这个参数时,有默认值

@NotNull

源码英文解释,按照自己的理解翻译对应中文如下

/**
 * The annotated element must not be {@code null}. 添加此注解的元素的值不能为 null
 * Accepts any type. 接受所有类型
 *
 * @author Emmanuel Bernard
 */

使用示例

@NotNull(message = "用户名不能为空")
private String username;
  • message 参数

    元素值无效时所提示的信息,不写这个参数时,有默认值

@Null

源码英文解释,按照自己的理解翻译对应中文如下

/**
 * The annotated element must be {@code null}. 添加此注解的元素的值必须为 null
 * Accepts any type. 接受所有类型
 *
 * @author Emmanuel Bernard
 */

使用示例

@Null(message = "该属性值必须为 null")
private String nullValue;
  • message 参数

    元素值无效时所提示的信息,不写这个参数时,有默认值

@Past

源码英文解释,按照自己的理解翻译对应中文如下

/**
 * The annotated element must be an instant, date or time in the past. 被添加此注解的元素的值必须是过去的某个时刻、日期或时间。
 * <p>
 * <i>Now</i> is defined by the {@link ClockProvider} attached to the {@link Validator} or
 * {@link ValidatorFactory}. The default {@code clockProvider} defines the current time
 * according to the virtual machine, applying the current default time zone if needed.
 * 现在,是由附加到 Validator 接口或 ValidatorFactory 接口的 ClockProvider 定义的。默认的 clockProvider 根据虚拟机定义当前时间,如果需要,应用当
 * 前默认时区。
 * <p>
 * Supported types are: 支持的类型如下:
 * <ul>
 *     <li>{@code java.util.Date}</li>
 *     <li>{@code java.util.Calendar}</li>
 *     <li>{@code java.time.Instant}</li>
 *     <li>{@code java.time.LocalDate}</li>
 *     <li>{@code java.time.LocalDateTime}</li>
 *     <li>{@code java.time.LocalTime}</li>
 *     <li>{@code java.time.MonthDay}</li>
 *     <li>{@code java.time.OffsetDateTime}</li>
 *     <li>{@code java.time.OffsetTime}</li>
 *     <li>{@code java.time.Year}</li>
 *     <li>{@code java.time.YearMonth}</li>
 *     <li>{@code java.time.ZonedDateTime}</li>
 *     <li>{@code java.time.chrono.HijrahDate}</li>
 *     <li>{@code java.time.chrono.JapaneseDate}</li>
 *     <li>{@code java.time.chrono.MinguoDate}</li>
 *     <li>{@code java.time.chrono.ThaiBuddhistDate}</li>
 * </ul>
 * <p>
 * {@code null} elements are considered valid. 属性值为 null 时被认为是有效的
 *
 * @author Emmanuel Bernard
 */

使用示例

@Past(message = "值必须是过去的某个时刻、日期或时间")
private Date pastValue;
  • message 参数

    元素值无效时所提示的信息,不写这个参数时,有默认值

@PastOrPresent

源码英文解释,按照自己的理解翻译对应中文如下

/**
 * The annotated element must be an instant, date or time in the past or in the present. 
 * 被添加此注解的元素的值必须是过去或现在的时刻、日期或时间。
 * <p>
 * <i>Now</i> is defined by the {@link ClockProvider} attached to the {@link Validator} or
 * {@link ValidatorFactory}. The default {@code clockProvider} defines the current time
 * according to the virtual machine, applying the current default time zone if needed.
 * 现在,是由附加到 Validator 接口或 ValidatorFactory 接口的 ClockProvider 定义的。默认的 clockProvider 根据虚拟机定义当前时间,如果需要,应用当
 * 前默认时区。
 * <p>
 * The notion of present is defined relatively to the type on which the constraint is
 * used. For instance, if the constraint is on a {@link Year}, present would mean the whole
 * current year.
 * 这里的 present 概念是相对于使用约束的类型定义的。例如,如果约束是在 Year 上,present表示整个当前年份。
 * <p>
 * Supported types are: 支持的类型如下:
 * <ul>
 *     <li>{@code java.util.Date}</li>
 *     <li>{@code java.util.Calendar}</li>
 *     <li>{@code java.time.Instant}</li>
 *     <li>{@code java.time.LocalDate}</li>
 *     <li>{@code java.time.LocalDateTime}</li>
 *     <li>{@code java.time.LocalTime}</li>
 *     <li>{@code java.time.MonthDay}</li>
 *     <li>{@code java.time.OffsetDateTime}</li>
 *     <li>{@code java.time.OffsetTime}</li>
 *     <li>{@code java.time.Year}</li>
 *     <li>{@code java.time.YearMonth}</li>
 *     <li>{@code java.time.ZonedDateTime}</li>
 *     <li>{@code java.time.chrono.HijrahDate}</li>
 *     <li>{@code java.time.chrono.JapaneseDate}</li>
 *     <li>{@code java.time.chrono.MinguoDate}</li>
 *     <li>{@code java.time.chrono.ThaiBuddhistDate}</li>
 * </ul>
 * <p>
 * {@code null} elements are considered valid. 属性值为 null 时被认为是有效的
 *
 * @author Guillaume Smet
 * @since 2.0
 */

使用示例

@PastOrPresent(message = "值必须是过去或现在的时刻、日期或时间")
private Date pastOrPresentValue;
  • message 参数

    元素值无效时所提示的信息,不写这个参数时,有默认值

@Pattern

源码英文解释,按照自己的理解翻译对应中文如下

/**
 * The annotated {@code CharSequence} must match the specified regular expression. 
 * 被添加此注解的元素的值必须匹配指定的正则表达式。
 * The regular expression follows the Java regular expression conventions 正则表达式遵循 Java 正则表达式约定
 * see {@link java.util.regex.Pattern}.
 * <p>
 * Accepts {@code CharSequence}. {@code null} elements are considered valid. 接收 CharSequence 接口,属性值为 null 时被认为是有效的
 *
 * @author Emmanuel Bernard
 */

使用示例

@Pattern(regexp = "^[0-9]*$", message = "字符串的值只能包含 0-9 的数字")
private String patternValue;
  • regexp 参数

    元素要匹配的正则表达式

  • Flag 参数

    解析正则表达式时考虑的Flag 数组

  • message 参数

    元素值无效时所提示的信息,不写这个参数时,有默认值

@Positive

源码英文解释,按照自己的理解翻译对应中文如下

/**
 * The annotated element must be a strictly positive number (i.e. 0 is considered as an
 * invalid value). 添加此注解的元素的值必须是严格的正数(即 0 被视为无效值)。
 * <p>
 * Supported types are: 支持的类型如下:
 * <ul>
 *     <li>{@code BigDecimal}</li>
 *     <li>{@code BigInteger}</li>
 *     <li>{@code byte}, {@code short}, {@code int}, {@code long}, {@code float},
 *     {@code double} and their respective wrappers</li> byte,short,int,long,floatm,double 以及它们各自的封装器
 * </ul>
 * <p>
 * {@code null} elements are considered valid.  属性值为 null 时被认为是有效的
 *
 * @author Gunnar Morling
 * @since 2.0
 */

使用示例

@Positive(message = "值必须为正数")
private Integer positiveValue;
  • message 参数

    元素值无效时所提示的信息,不写这个参数时,有默认值

@PositiveOrZero

源码英文解释,按照自己的理解翻译对应中文如下

/**
 * The annotated element must be a positive number or 0. 添加此注解的元素的值必须正数 或 0
 * <p>
 * Supported types are: 支持的类型如下:
 * <ul>
 *     <li>{@code BigDecimal}</li>
 *     <li>{@code BigInteger}</li>
 *     <li>{@code byte}, {@code short}, {@code int}, {@code long}, {@code float},
 *     {@code double} and their respective wrappers</li>  byte,short,int,long,floatm,double 以及它们各自的封装器
 * </ul>
 * <p>
 * {@code null} elements are considered valid. 属性值为 null 时被认为是有效的
 *
 * @author Gunnar Morling
 * @since 2.0
 */

使用示例

@PositiveOrZero(message = "值必须为正数或 0")
private Integer positiveOrZeroValue;
  • message 参数

    元素值无效时所提示的信息,不写这个参数时,有默认值

@Size

源码英文解释,按照自己的理解翻译对应中文如下

/**
 * The annotated element size must be between the specified boundaries (included). 添加此注解的元素的值的大小必须在指定的边界(包括)之间。
 * <p>
 * Supported types are: 支持的类型如下
 * <ul>
 *     <li>{@code CharSequence} (length of character sequence is evaluated)</li>
 *     <li>{@code Collection} (collection size is evaluated)</li>
 *     <li>{@code Map} (map size is evaluated)</li>
 *     <li>Array (array length is evaluated)</li>
 * </ul>
 * <p>
 * {@code null} elements are considered valid. 属性值为 null 时被认为是有效的
 *
 * @author Emmanuel Bernard
 */

使用示例

@Size(min = 1, max = 3, message = "字符串长度必须在 1-3 之间(包括 1 和 3 )")
private String sizeValue;
  • min 参数

    最小长度

  • max 参数

    最大长度

  • message 参数

    元素值无效时所提示的信息,不写这个参数时,有默认值

快速入门

1、添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

2、在对应 Entity 类上的对应字段添加对应注解

public class User {
    private Integer id;
    @NotNull(message = "用户名不能为空")
    @NotBlank(message = "用户名不能为空")
    private String username;

    @NotBlank(message = "值不能为 null 且长度大于等于1")
    @NotEmpty(message = "值不能为 null 或为空")
    private String password;

    @Email(regexp = "[a-z|A-Z|0-9].*@qq\\.com", message = "请输入正确的qq邮箱")
    private String email;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "User2{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

3、在接收 Entity类 参数位置添加 注解 @Validated

@RestController
@RequestMapping("/validation")
public class TestController {

    @PostMapping
    public void report(@RequestBody @Validated User user) {
        System.out.println(user);
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员陈_明勇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值