欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

springboot中validator数据校验功能的实现

程序员文章站 2022-06-17 23:02:19
普通校验导入依赖:默认的报错:没有提示具体的属性设置自己的错误信息提示:创建 validationmessages.properties内容如下:user.id.notnull = id 不能为空us...

普通校验

导入依赖:

springboot中validator数据校验功能的实现

默认的报错:没有提示具体的属性

springboot中validator数据校验功能的实现

设置自己的错误信息提示:创建 validationmessages.properties

springboot中validator数据校验功能的实现

内容如下:

user.id.notnull = id 不能为空
user.username.size = username 长度为5-10
user.age.min = age 年龄最小为1
user.age.max = age 年龄最大为100
user.email.pattern= email 格式不正确

实体类注解上设置message属性,,使用{}引入 vallidationmessages.properties 内容:

public class user {
    @notnull(message = "{user.id.notnull}")
    private integer id;
    @size(min = 5,max = 10,message = "{user.username.size}")  // @size  字符串长度
    private string username;
    @decimalmin(value = "1",message = "{user.age.min}") // @decimalmin 数值最小
    @decimalmax(value = "100",message = "{user.age.max}")
    private integer age;
    @email(message = "{user.email.pattern}")
    private string  email;
}

测试:

springboot中validator数据校验功能的实现

自定义错误信息,显示指定属性错误

分组校验

不同的请求,实现不同的校验。。

创建两个空接口,标识作用:

validationgroup01 validationgroup02

修改user:

public class user {
    @notnull(message = "{user.id.notnull}",groups = {validationgroup01.class,validationgroup02.class})
    private integer id;
    @size(min = 5,max = 10,message = "{user.username.size}",groups = {validationgroup01.class})  // @size  字符串长度
    private string username;
    @decimalmin(value = "1",message = "{user.age.min}") // @decimalmin 数值最小
    @decimalmax(value = "100",message = "{user.age.max}")
    private integer age;
    @email(message = "{user.email.pattern}",groups = {validationgroup01.class})
    private string  email;
}

controller中表明你要使用哪个分组校验:

    public void adduser(@validated(value = validationgroup01.class) user user, bindingresult result){
     		...
    }

只会校验user中groups标注了validationgroup01.class 的字段。。

到此这篇关于springboot中validator数据校验的文章就介绍到这了,更多相关springboot validator数据校验内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!