Spring boot validation校验

使用 Hibernate validator 的步骤:
1. 在 Pojo 类的字段上, 加上 Hibernate validator 注解
2. 在Controller 函数的形参前加上 @Valid 或 @Validated 注解, 触发一次validation.
3. 在每个 @Valid 或 @Validated 注解参数后, 紧跟一个 BindingResult 类型的参数. 如果没有提供对应的 BindingResult 参数, Spring MVC 将抛出异常.
4. 在Controller 函数中, 通过 BindingResult 类型的参数获取检验的结果.

@Null 被注释的元素必须为 null
@NotNull 被注释的元素必须不为 null
@NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty 检查约束元素不能为NULL或者是EMPTY.
@AssertTrue 被注释的元素必须为 true
@AssertFalse 被注释的元素必须为 false
@Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max, min) 注释的元素的长度必须在指定的范围内, 支持字符串和集合
@Length(min=, max=) 被注释的字符串的大小必须在指定的范围内
@Email 被注释的元素必须是电子邮箱地址
@Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
@Range(min=, max=) 被注释的元素必须在合适的范围内
@Past 被注释的元素必须是一个过去的日期
@Future 被注释的元素必须是一个将来的日期
@Pattern(value) 被注释的元素必须符合指定的正则表达式
@URL(protocol=,
host=, port=,
regexp=, flags=) 被注释的字符串必须是一个有效的url
@CreditCardNumber 被注释的字符串必须通过Luhn校验算法,
银行卡,信用卡等号码一般都用Luhn
计算合法性


@Valid 和 @Validated 注解
====================================
@Valid 和 @Validated 都用来触发一次校验, @Valid 是 JSR 303规范的注解, @Validated 是Spring 加强版的注解, 加强的地方有:
@Validated 支持组序列, 该特性用的较少,所以, 推荐使用 @Validated 注解.


pom.xml
----------------------------------

<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>


POJO 类
----------------------------------
public class Book {
@Null(message = "bookId should be null when add", groups = { AddEntity.class })
@NotNull(message = "bookId should be not null when update and delete", groups = { UpdateEntity.class, DeleteEntity.class })
private Integer bookId;

private String author;

public Integer getBookId() {
return bookId;
}

public void setBookId(Integer bookId) {
this.bookId = bookId;
}

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}

}

Controller 类
----------------------------------
@RestController
@RequestMapping("/bookApi")
class BookController {

// 新增操作
// Book 参数要加上 @RequestBody
// book 参数加上 @Validated 验证指令
@PostMapping("/books")
public Book addBook(@Validated({ AddEntity.class }) @RequestBody Book book, BindingResult bookBinding) {
if (bookBinding.hasErrors()) {
List<ObjectError> errors = bookBinding.getAllErrors();
errors.stream()
.map(e -> e.getObjectName() + "," + e.getDefaultMessage())
.forEach(System.out::println);
return null;
}
book.setBookId(100);
return book;
}

// 更新操作
@PutMapping("/books/{bookId}")
public Book updateBook(@Validated({ UpdateEntity.class }) @RequestBody Book book, BindingResult bookBinding) {
if (bookBinding.hasErrors()) {
List<ObjectError> errors = bookBinding.getAllErrors();
errors.stream()
.map(e -> e.getObjectName() + "," + e.getDefaultMessage())
.forEach(System.out::println);
return null;
}
return book;
}

// list all 操作
@GetMapping("/books")
public List<Book> listBooks() {
List<Book> books = new ArrayList<Book>();
Book book;
book = new Book();
book.setBookId(20);
books.add(book);
return books;
}
}


参考:https://www.cnblogs.com/harrychinese/p/SpringBoot_pojo_validation.html

实体类在属性上常用的注解有
@NotEmpty(message="姓名不能为空")
private String name;
@NotEmpty(message="密码不能为空")
@Length(min=6,message="密码长度不能小于6位")
@size (min=3, max=20, message="用户名长度只能在3-20之间")
@size (min=6, max=20, message="密码长度只能在6-20之间")
@pattern (regexp="[a-za-z0-9._%+-]+@[a-za-z0-9.-]+\.[a-za-z]{2,4}", message="邮件格式错误")
@Length(min = 5, max = 20, message = "用户名长度必须位于5到20之间")
@Email(message = "比如输入正确的邮箱")
@NotNull(message = "用户名称不能为空")
@Max(value = 100, message = "年龄不能大于100岁")
@Min(value= 18 ,message= "必须年满18岁!" )
@AssertTrue(message = "bln4 must is true")
@AssertFalse(message = "blnf must is falase")
@DecimalMax(value="100",message="decim最大值是100")
DecimalMin(value="100",message="decim最小值是100")
@NotNull(message = "身份证不能为空")
@Pattern(regexp="^(\d{18,18}|\d{15,15}|(\d{17,17}[x|X]))$", message="身份证格式错误")

原文地址:https://www.cnblogs.com/shy1766IT/p/9999632.html