参数校验这东西困扰好久了,之前也没有去弄,今天抽点时间自己稍微记录一下,以便自己后期要用的时候随用随取

先引入依赖

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.4.1.Final</version>
</dependency>
@AssertTrue   //用于boolean字段,该字段只能为true   

@AssertFalse //该字段的值只能为false   

@CreditCardNumber //对信用卡号进行一个大致的验证   

@DecimalMax //只能小于或等于该值   

@DecimalMin //只能大于或等于该值   

@Digits (integer= 2 ,fraction= 20 ) //检查是否是一种数字的整数、分数,小数位数的数字。   

@Email //检查是否是一个有效的email地址   

@Future //检查该字段的日期是否是属于将来的日期   

@Length (min=,max=) //检查所属的字段的长度是否在min和max之间,只能用于字符串   

@Max //该字段的值只能小于或等于该值   

@Min //该字段的值只能大于或等于该值   

@NotNull //不能为null   

@NotBlank //不能为空,检查时会将空格忽略   

@NotEmpty //不能为空,这里的空是指空字符串   

@Null //检查该字段为空   

@Past //检查该字段的日期是在过去   

@Size (min=, max=) //检查该字段的size是否在min和max之间,可以是字符串、数组、集合、Map等   

@URL (protocol=,host,port) //检查是否是一个有效的URL,如果提供了protocol,host等,则该URL还需满足提供的条件   

@Valid //该注解只要用于字段为一个包含其他对象的集合或map或数组的字段,或该字段直接为一个其他对象的引用,  

首先试试@Email

故意将Email 格式填错误的,返回的参数是

{
    "timestamp":"2020-03-17T06:39:35.696+0000",
    "status":400,
    "error":"Bad Request",
    "errors":[
        {
            "codes":[
                "Email.user.email",
                "Email.email",
                "Email.java.lang.String",
                "Email"
            ],
            "arguments":[
                {
                    "codes":[
                        "user.email",
                        "email"
                    ],
                    "arguments":null,
                    "defaultMessage":"email",
                    "code":"email"
                },
                [

                ],
                {
                    "arguments":null,
                    "defaultMessage":".*",
                    "codes":[
                        ".*"
                    ]
                }
            ],
            "defaultMessage":"email 格式不对",
            "objectName":"user",
            "field":"email",
            "rejectedValue":"23434554",
            "bindingFailure":false,
            "code":"Email"
        }
    ],
    "message":"Validation failed for object='user'. Error count: 1",
    "path":"/user/addUser"
}

然后用户名不填

{
    "timestamp":"2020-03-17T06:42:44.090+0000",
    "status":400,
    "error":"Bad Request",
    "errors":[
        {
            "codes":[
                "NotNull.user.userName",
                "NotNull.userName",
                "NotNull.java.lang.String",
                "NotNull"
            ],
            "arguments":[
                {
                    "codes":[
                        "user.userName",
                        "userName"
                    ],
                    "arguments":null,
                    "defaultMessage":"userName",
                    "code":"userName"
                }
            ],
            "defaultMessage":"用户名不能为空",
            "objectName":"user",
            "field":"userName",
            "rejectedValue":null,
            "bindingFailure":false,
            "code":"NotNull"
        }
    ],
    "message":"Validation failed for object='user'. Error count: 1",
    "path":"/user/addUser"
}

每一个 都可以试试

下面是各个版本 完整的表格 引用自csdn

5.1.1. Bean Validator内置的注解

Annotation支持的数据类型作用Hibernate metadata impact
@AssertFalseBoolean, boolean判断关联属性是否为布尔值false没有
@AssertTrueBoolean, booleanChecks that the annotated element istrue.没有
@DecimalMaxBigDecimal, BigInteger, String, byte, short, int,long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number.被注解的值必须不大于约束中指定的最大值. 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.没有
@DecimalMinBigDecimal, BigInteger, String, byte, short, int,long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number.被注解的值必须不小于约束中指定的最小值. 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.没有
@Digits(integer=, fraction=)BigDecimal, BigInteger, String, byte, short, int,long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number.校验整数位数和小数位数对应的数据库表字段会被设置精度(precision)和准度(scale).
@Futurejava.util.Date, java.util.Calendar; Additionally supported by HV, if the Joda Time date/time API is on the class path: any implementations of ReadablePartial and ReadableInstant.检查给定的日期是否比现在晚.没有
@MaxBigDecimal, BigInteger, byte, short, int, longand the respective wrappers of the primitive types. Additionally supported by HV: String(the numeric value represented by a String is evaluated), any sub-type of Number.检查该值是否小于或等于约束条件中指定的最大值.会给对应的数据库表字段添加一个check的约束条件.
@MinBigDecimal, BigInteger, byte, short, int, longand the respective wrappers of the primitive types. Additionally supported by HV: String(the numeric value represented by a String is evaluated), any sub-type of Number.检查该值是否大于或等于约束条件中规定的最小值.会给对应的数据库表字段添加一个check的约束条件.
@NotNullAny typeChecks that the annotated value is notnull.对应的表字段不允许为null.
@NullAny typeChecks that the annotated value is null.没有
@Pastjava.util.Date, java.util.Calendar; Additionally supported by HV, if the Joda Time date/time API is on the class path: any implementations of ReadablePartial and ReadableInstant.检查注解对象中的值表示的日期比当前早.没有
@Pattern(regex=, flag=)String检查该字符串是否能够在match指定的情况下被regex定义的正则表达式匹配.没有
@Size(min=, max=)String, Collection, Map and arrays校验对象的size。本文作者认为前提是该对象有size()方法,String除外。对应的数据库表字段的长度会被设置成约束中定义的最大值.
@ValidAny non-primitive type递归的对关联对象进行校验, 如果关联对象是个集合或者数组, 那么对其中的元素进行递归校验,如果是一个map,则对其中的值部分进行校验.没有

5.1.2. Hibernate Validator拓展的注解

Annotation支持的数据类型作用Hibernate metadata impact
@CreditCardNumberString校验信用卡号码没有
@EmailString校验邮件地址没有
@Length(min=, max=)String功能同@Size,但是只支持String类型对应的数据库表字段的长度会被设置成约束中定义的最大值.
@NotBlankString不为null,不为空值,不为全空格。功能强大于@NotEmpty没有
@NotEmptyString,Collection,Map and arrays校验是否为null或者为空值。功能强于@NotNull没有
@Range(min=, max=)BigDecimal,BigInteger,String, byte,short, int,long and the respective wrappers of the primitive types判断数值的范围,不仅支持数值类型,还支持字符串、字节等等类型没有
@SafeHtml(whitelistType=, additionalTags=)CharSequence无使用价值没有
@ScriptAssert(lang=, script=, alias=)Any type无使用价值没有
@URL(protocol=, host=, port=, regexp=, flags=)StringChecks if the annotated string is a valid URL according to RFC2396. If any of the optional parameters protocol, host or port are specified, the corresponding URL fragments must match the specified values. The optional parametersregexp and flags allow to specify an additional regular expression (including regular expression flags) which the URL must match.没有

5.1.3. Validator框架拓展注解

Annotation支持的数据类型作用
@NotEmptyPatternString在字符串不为空的情况下,验证是否匹配正则表达式
@ListStringPatternList验证集合中的字符串是否满足正则表达式
@DateValidatorString验证日期格式是否满足正则表达式,Local为ENGLISH
@DateFormatCheckPatternString验证日期格式是否满足正则表达式,Local为自己手动指定