1.引入依赖
mvn仓库https://search.maven.org/
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.2.5.Final</version>
</dependency>
这里需要注意,如果程序用jdk1.8,但是引入的依赖版本过高,会出现jar包依赖的jdk高于程序依赖的jdk的错误,如下所示:
类文件具有错误的版本 55.0, 应为 52.0
请删除该文件或确保该文件位于正确的类路径子目录中。
引入低版本的hibernate-validator即可解决该问题。详情
2.创建实体
package com.yangjunbo.helloword.pojo;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.*;
public class User {
@NotBlank(message = "姓名不允许为空!")
@Length(min = 2,max = 10,message = "姓名长度错误,姓名长度2-10!")
private String name;
@NotNull(message = "年龄不能为空!")
@Min(18)
private int age;
@NotBlank(message = "地址不能为空!")
private String address;
@Pattern(regexp = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$", message = "手机号格式错误")
private String phone;
@Email(message = "邮箱格式错误")
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
3.创建API路由
@PostMapping(path = "/check")
public String check(@RequestBody @Valid User user, BindingResult result) {
String name = user.getName();
if(result.hasErrors()) {
List<ObjectError> list = result.getAllErrors();
for (ObjectError error : list) {
System.out.println(error.getCode()+ "-" + error.getDefaultMessage());
}
}
return name;
}
4.使用postman模拟请求
5.查看控制台输入,验证测试结果