SpringBoot-表单验证-统一异常处理-自定义验证信息源( 七 )

8.2 添加信息源文件├───resources└── messages└── validation└── messages.properties# messages.propertiesname.not.empty=用户名不能为空email.not.valid=${validatedValue}是邮箱地址?email.not.empty=邮箱不能为空phone.not.valid=${validatedValue}是手机号?phone.not.empty=手机号不能为空password.size.valid=密码长度必须在{min}-{max}之间id.not.empty=主键不能为空8.3 修改实体类import com.ldx.valid.annotation.Phone;import lombok.Data;import org.hibernate.validator.constraints.Range;import javax.validation.constraints.*;import java.io.Serializable;/** * 用户信息管理 * @author ludangxin * @date 2021/8/5 */@Datapublic class SysUser implements Serializable {private static final long serialVersionUID = 1L;/*** 主键*/@NotNull(message = "{id.not.empty}", groups = {ValidationInterface.update.class})private Long id;/*** 用户名*/@NotEmpty(message = "{name.not.empty}", groups = {ValidationInterface.update.class,ValidationInterface.add.class})private String username;/*** 密码*/@Size(min = 6, max = 16, message = "{password.size.valid}", groups = {ValidationInterface.update.class,ValidationInterface.add.class})private String password = "123456";/*** 邮箱地址*/@Email(message = "{email.not.valid}",groups = {ValidationInterface.update.class,ValidationInterface.add.class,ValidationInterface.select.class})@NotEmpty(message = "{email.not.empty}", groups = ValidationInterface.add.class)private String email;/*** 电话*/@Pattern(message = "{phone.not.valid}", regexp = "^1[3456789]\d{9}$",groups = {ValidationInterface.add.class})@NotEmpty(message = "{phone.not.empty}", groups = {ValidationInterface.add.class})private String phone;}8.4 启动测试? 输入错误的邮箱地址测试:

SpringBoot-表单验证-统一异常处理-自定义验证信息源

文章插图
 
9. 预置注解清单 注解
说明
@Null
限制只能为null
@NotNull
限制必须不为null
@AssertFalse
限制必须为false
@AssertTrue
限制必须为true
@DecimalMax(value)
限制必须为一个不大于指定值的数字
@DecimalMin(value)
限制必须为一个不小于指定值的数字
@Digits(integer,fraction)
限制必须为一个小数,且整数部分的位数不能超过integer,小数部分的位数不能超过fraction
@Future
限制必须是一个将来的日期
@Max(value)
限制必须为一个不大于指定值的数字
@Min(value)
限制必须为一个不小于指定值的数字
@Past
限制必须是一个过去的日期
@Pattern(value)
限制必须符合指定的正则表达式
@Size(max,min)
限制字符长度必须在min到max之间
@Past
验证注解的元素值(日期类型)比当前时间早
@NotEmpty
验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0)
@NotBlank
验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank
@Email
验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式
原文链接:
https://www.cnblogs.com/ludangxin/p/15113954.html
作者:张铁牛
如果觉得本文对你有帮助,可以转发关注支持一下




推荐阅读