【Spring】Bean Validation

 

参考:

https://www.baeldung.com/java-validation

https://www.baeldung.com/java-bean-validation-not-null-empty-blank

https://www.baeldung.com/spring-mvc-custom-validator  定制自己的校验器

https://segmentfault.com/a/1190000023471742


 @Valid  vs  @Validated

区别@Valid@Validated
提供者 JSR-303规范 Spring
是否支持分组 不支持 支持
标注位置 METHOD, FIELD, CONSTRUCTOR, PARAMETER, TYPE_USE TYPE, METHOD, PARAMETER
嵌套校验 支持 不支持

 

maven依赖

In the latest version of spring-boot-starter-validation, besides other dependencies, transitive dependency of hibernate-validator will be available.

If you want to add just the dependency for validation you can simply add the hibernate-validator in you pom.xml.

A quick note: hibernate-validator is entirely separate from the persistence aspects of Hibernate. So, by adding it as a dependency, we're not adding these persistence aspects into the project.

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.10.Final</version>
</dependency>

 

基本注解:

  • @NotNull validates that the annotated property value is not null.
  • @AssertTrue validates that the annotated property value is true.
  • @Size validates that the annotated property value has a size between the attributes min and max; can be applied to StringCollectionMap, and array properties.
  • @Min validates that the annotated property has a value no smaller than the value attribute.
  • @Max validates that the annotated property has a value no larger than the value attribute.
  • @Email validates that the annotated property is a valid email address.

Some annotations accept additional attributes, but the message attribute is common to all of them. This is the message that will usually be rendered when the value of the respective property fails validation.

And some additional annotations that can be found in the JSR:

  • @NotEmpty validates that the property is not null or empty; can be applied to StringCollectionMap or Array values.
  • @NotBlank can be applied only to text values and validates that the property is not null or whitespace.
  • @Positive and @PositiveOrZero apply to numeric values and validate that they are strictly positive, or positive including 0.
  • @Negative and @NegativeOrZero apply to numeric values and validate that they are strictly negative, or negative including 0.
  • @Past and @PastOrPresent validate that a date value is in the past or the past including the present; can be applied to date types including those added in Java 8.
  • @Future and @FutureOrPresent validate that a date value is in the future, or in the future including the present.

 

posted @ 2023-08-09 22:36  飞翔在天  阅读(6)  评论(0编辑  收藏  举报