根据groups来指定需要校验的字段
class StudentRequest {@
NotNull(message = "id不能为空!", groups = {
AddGroup.class
}) Integer id;@
NotBlank(message = "姓名不能为空", groups = {
AddGroup.class, UpdateGroup.class
}) String name;
public interface Update {}
public interface Add {}
}
//添加分组 public interface AddGroup {
}
//更新分组 public interface UpdateGroup {
}
在做更新时,校验如下:
ValidatorUtils.validateEntity(gatherForm, Update.class);
在做新增时,校验如下
ValidatorUtils.validateEntity(gatherForm, Add.class);
ValidatorUtils 校验工具代码
/** * hibernate-validator校验工具类 * * 参考文档:http://docs.jboss.org/hibernate/validator/5.4/reference/en-US/html_single/ * * @author Mark sunlightcs@gmail.com */
public class ValidatorUtils {
private static Validator validator;
static {
validator = Validation.buildDefaultValidatorFactory().getValidator();
} /** * 校验对象 * @param object 待校验对象 * @param groups 待校验的组 * @throws RRException 校验不通过,则报RRException异常 */
public static void validateEntity(Object object, Class <? > ...groups) throws RRException {
Set < ConstraintViolation < Object >> constraintViolations = validator.validate(object, groups);
if (!constraintViolations.isEmpty()) {
StringBuilder msg = new StringBuilder();
for (ConstraintViolation < Object > constraint: constraintViolations) {
msg.append(constraint.getMessage()).append("<br>");
}
throw new RRException(msg.toString());
}
}
}
来源:https://juejin.cn/post/6914836785751457800
没有回复内容