springboot引入Hibernate-Validator
依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
常用注解
@Length 长度校验
@Pattern 格式校验(正则表达式)
@Email 邮箱格式校验
@Max 最大值校验
@Min 最小值校验
@Range 范围校验,Min和Max的组合
@NotBlank 不为空白字符的校验
@NotEmpty 数组、集合等不为空的校验
@NotNull 空指针校验
....
@Length(min = 11, max = 11, message = "手机号不合法,请输入合法的11位手机号")
@NotBlank(message = "备注不能为空") message:自定义提示信息
Example
实体类
package com.sheep.emo.pojo;
import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
* (GroupBuyingOrganizer)实体类
*
* @author makejava
* @since 2022-07-28 21:32:20
*/
@Getter
@Setter
@ToString
public class GroupBuyingOrganizer implements Serializable {
private static final long serialVersionUID = -97810184898686414L;
/**
* 主键id
*/
@TableId(type = IdType.AUTO)
private Long id;
/**
* 联系方式
*/
@NotBlank
private String phoneNumber;
/**
* 店铺名称
*/
private String storeName;
/**
* 推荐团长
*/
private String recommendGroupBuyingOrganizer;
/**
* 提货地址
*/
private String receiverAddress;
/**
* 佣金余额
*/
private BigDecimal commissionBalance;
/**
* 收益总额
*/
private BigDecimal earningsBalance;
/**
* 现金余额
*/
private BigDecimal cashBalance;
/**
* 团长状态 1:启用 2:禁用
*/
private String groupBuyingOrganizerStatus;
/**
* 备注
*/
private String remark;
/**
* 推荐人
*/
private String referrer;
/**
* 申请时间
*/
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
private Date applyTime;
/**
* 审核状态 1:待审核 2:审核中 3:通过 4:不予通过
*/
private String auditStatus;
/**
* 创建时间
*/
@JSONField(serialize = false)
private Date createTime;
/**
* 更新时间
*/
@JSONField(serialize = false)
private Date updateTime;
}
工具类
package com.sheep.emo.utils;
import com.sheep.emo.pojo.GroupBuyingOrganizer;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author : sheep669
* @description : TODO
* @created at 2022/8/2 11:50
*/
public class ValidatorUtil {
private static Validator validator;
static {
validator = Validation.buildDefaultValidatorFactory().getValidator();
}
public static List<String> valid(GroupBuyingOrganizer groupBuyingOrganizer) {
Set<ConstraintViolation<GroupBuyingOrganizer>> validate = validator.validate(groupBuyingOrganizer);
List<String> list = validate
.stream()
.map(v -> "属性:" + v.getPropertyPath() +
",属性的值:" + v.getInvalidValue()
+ ",校验不通过信息:" + v.getMessage())
.collect(Collectors.toList());
return list;
}
}
测试
@Test
public void testValidator() {
GroupBuyingOrganizer groupBuyingOrganizer = new GroupBuyingOrganizer();
// groupBuyingOrganizer.setPhoneNumber("12314003693");
groupBuyingOrganizer.setRemark("是好人ya");
List<String> valid = ValidatorUtil.valid(groupBuyingOrganizer);
System.out.println(valid);
}
console
[属性:phoneNumber,属性的值:null,校验不通过信息:不能为空]
Util还可以这样写
package com.sheep.emo.utils;
import com.sheep.emo.pojo.GroupBuyingOrganizer;
import org.hibernate.validator.HibernateValidator;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author : sheep669
* @description : TODO
* @created at 2022/8/2 11:50
*/
public class ValidatorUtil {
private static Validator validator;
private static ValidatorFactory validatorFactory = Validation
.byProvider(HibernateValidator.class)
.configure()
// true 遇到一个错误立即返回 | false 全部校验完一起返回
.failFast(true)
.buildValidatorFactory();
static {
validator = validatorFactory.getValidator();
}
public static List<String> valid(GroupBuyingOrganizer groupBuyingOrganizer) {
Set<ConstraintViolation<GroupBuyingOrganizer>> validate = validator.validate(groupBuyingOrganizer);
List<String> list = validate
.stream()
.map(v -> "属性:" + v.getPropertyPath() +
",属性的值:" + v.getInvalidValue()
+ ",校验不通过信息:" + v.getMessage())
.collect(Collectors.toList());
return list;
}
}
实体类
/**
* 联系方式
*/
@NotBlank(message = "手机号不能为空")
private String phoneNumber;
/**
* 备注
*/
@NotBlank(message = "备注不能为空")
private String remark;
测试
@Test
public void testValidator() {
GroupBuyingOrganizer groupBuyingOrganizer = new GroupBuyingOrganizer();
// groupBuyingOrganizer.setPhoneNumber("12314003693");
// groupBuyingOrganizer.setRemark("是好人ya");
List<String> valid = ValidatorUtil.valid(groupBuyingOrganizer);
System.out.println(valid);
}
console
[属性:phoneNumber,属性的值:null,校验不通过信息:手机号不能为空]
格式验证
@Pattern
@Pattern(regexp = "^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[A-Za-z0-9]{6,20}$", message = "用户名错误")