Validate
- Spring Validation
- Hibernate Validator
Spring Validation最佳实践及其实现原理,参数校验没那么简单!精讲解简洁
Hibernate Validator -对象基础验证(一)(可能是东半球最全的讲解了)
Hibernate validators unit testing
public class UserTest {
private Validator validator;
@BeforeEach
void setupValidatorInstance() {
validator = Validation.buildDefaultValidatorFactory().getValidator();
}
@Test
public void setUsername_validateFail_ifSetNull() {
User user = User.builder().username(null).password("123").build();
Set<ConstraintViolation<User>> violations = validator.validate(user);
assertEquals(1, violations.size());
}
}
class StudentValidator extends Specification {
@Autowired
private Validator validator
def testStudent() {
Student student = new Student();
student.setName("");
student.setAge(3)
student.setSalary(new BigDecimal("26.98765").setScale(4, RoundingMode.HALF_UP))
//整个对象完全校验
Set<ConstraintViolation<Student>> result = validator.validate(student);
//只校验某个属性
Set<ConstraintViolation<Student>> result2 = validator.validateProperty(student, "age");
//主动校验某个属性值是否合规
Set<ConstraintViolation<Student>> result3 = validator.validateValue(Student.class, "salary", new BigDecimal("123.3434"));
}
}
group
The first validate() call in Example 5.4, “Using validation groups” is done using no explicit group. There are no validation errors
定义一个接口,按顺序validate
package org.hibernate.validator.referenceguide.chapter05;
import javax.validation.GroupSequence;
import javax.validation.groups.Default;
@GroupSequence({ Default.class, CarChecks.class, DriverChecks.class })
public interface OrderedChecks {
}