Validate

  • Spring Validation
  • Hibernate Validator

Spring Validation最佳实践及其实现原理,参数校验没那么简单!精讲解简洁
Hibernate Validator -对象基础验证(一)(可能是东半球最全的讲解了)
Hibernate validators unit testing

  1. public class UserTest {
  2. private Validator validator;
  3. @BeforeEach
  4. void setupValidatorInstance() {
  5. validator = Validation.buildDefaultValidatorFactory().getValidator();
  6. }
  7. @Test
  8. public void setUsername_validateFail_ifSetNull() {
  9. User user = User.builder().username(null).password("123").build();
  10. Set<ConstraintViolation<User>> violations = validator.validate(user);
  11. assertEquals(1, violations.size());
  12. }
  13. }

  1. class StudentValidator extends Specification {
  2. @Autowired
  3. private Validator validator
  4. def testStudent() {
  5. Student student = new Student();
  6. student.setName("");
  7. student.setAge(3)
  8. student.setSalary(new BigDecimal("26.98765").setScale(4, RoundingMode.HALF_UP))
  9. //整个对象完全校验
  10. Set<ConstraintViolation<Student>> result = validator.validate(student);
  11. //只校验某个属性
  12. Set<ConstraintViolation<Student>> result2 = validator.validateProperty(student, "age");
  13. //主动校验某个属性值是否合规
  14. Set<ConstraintViolation<Student>> result3 = validator.validateValue(Student.class, "salary", new BigDecimal("123.3434"));
  15. }
  16. }

group

The first validate() call in Example 5.4, “Using validation groups” is done using no explicit group. There are no validation errors

定义一个接口,按顺序validate

  1. package org.hibernate.validator.referenceguide.chapter05;
  2. import javax.validation.GroupSequence;
  3. import javax.validation.groups.Default;
  4. @GroupSequence({ Default.class, CarChecks.class, DriverChecks.class })
  5. public interface OrderedChecks {
  6. }

字段上要定义分组 FieldChecks.class