public class Test{
private String field;
private String field2;
//自定义校验规则
@AssertTrue(message="个人基本信息-证件号码格式错误", groups = {Group.PC.class})
public boolean isValid() {
return "A".equals(this.field) ? isTrue(this.field2) : true;
}
}
public class ValidateUtil {
public static <T> void validate(T t, Class<?>... groups) throws ValidationException {
Validator validatorFactory = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<T>> errors = validatorFactory.validate(t, groups);
if (!errors.isEmpty()) {
for (ConstraintViolation<T> violation : errors) {
throw new ValidationException(violation.getMessage());
}
}
}
}
我在使用 ValidateUtil.validate(test),如果函数名是 isValid()可以校验,如果不带 is ,valid()就不能校验,求指教
1
Belmode 240 天前
public Boolean valid() 试试
|
2
ma836323493 240 天前
那你就进到 validatorFactory.validate 看看是怎么回事
|
4
abokchoy OP ```java
public final <T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups) { Contracts.assertNotNull(object, Messages.MESSAGES.validatedObjectMustNotBeNull()); ValidationContext<T> validationContext = this.getValidationContextBuilder().forValidate(object); if (!validationContext.getRootBeanMetaData().hasConstraints()) { return Collections.emptySet(); } else { ValidationOrder validationOrder = this.determineGroupValidationOrder(groups); ValueContext<?, Object> valueContext = ValueContext.getLocalExecutionContext(this.parameterNameProvider, object, validationContext.getRootBeanMetaData(), PathImpl.createRootPath()); return this.validateInContext(validationContext, valueContext, validationOrder); } } public <T> ValidationContext<T> forValidate(T rootBean) { Class<T> rootBeanClass = rootBean.getClass(); return new ValidationContext(this.constraintValidatorManager, this.messageInterpolator, this.constraintValidatorFactory, this.traversableResolver, (ExecutableParameterNameProvider)null, this.clockProvider, this.failFast, rootBean, rootBeanClass, this.beanMetaDataManager.getBeanMetaData(rootBeanClass), (Executable)null, (Object[])null, (Object)null); } ``` 反射拿了对象的类信息 |
5
sijue 240 天前
public class AssertTrueValidator implements ConstraintValidator<AssertTrue, Boolean> {
@Override public boolean isValid(Boolean bool, ConstraintValidatorContext constraintValidatorContext) { //null values are valid return bool == null || bool; } } public interface ConstraintValidator<A extends Annotation, T> { xxxx } -- 注解中指定的方法名是 isValid |
6
lvxiaomao 240 天前
报错信息贴一些呗
|
7
gitdoit 240 天前
|
8
chendy 239 天前
因为 valid 是一个普通方法,isValid 是 boolean 类型的 getter 方法
校验只校验 getter 方法(印象里好像还有字段 |