[英]How can I validate two or more fields in combination? in Methods
I hope you are very well.我希望你很好。
Right now I am developing a custom annotation to validates the arguments in a method, of this way:现在我正在开发一个自定义注释来验证 arguments 的方法,通过这种方式:
Interface:界面:
@Target({METHOD})
@Retention(RUNTIME)
@Constraint(validatedBy = ValidarImpl.class)
public @interface Validar {
public abstract String message() default "ERROR VALIDATION";
public abstract Class<?>[] groups() default {};
public abstract Class<? extends Payload>[] payload() default {};
}
Class: Class:
public class ValidarImpl implements ConstraintValidator<Validar, Object> {
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
return false;
}
}
Implementation of the annotation:注释的实现:
@Validar
public void method1 (@Positive int value, @Valid Car car){}
I am trying to obtain the name of the parameters and their value from ConstraintValidatorContext class with the intention validate the arguments of method1 method, however I haven't been able to do it yet我正在尝试从ConstraintValidatorContext class 获取参数的名称及其值,目的是验证method1方法的 arguments 方法,但是我还没有能够做到
I would like to do something like this: How can I validate two or more fields in combination?我想做这样的事情: 如何组合验证两个或多个字段? with methods.
用方法。
Thanks for your help.谢谢你的帮助。
You can refer to https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/?v=6.1#section-cross-parameter-constraints to get more details.您可以参考https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/?v=6.1#section-cross-parameter-constraints获取更多详细信息。
You can change your code as below:您可以按如下方式更改您的代码:
@SupportedValidationTarget(ValidationTarget.PARAMETERS)
public class ValidarImpl implements
ConstraintValidator < Validar, Object[] > {
@Override
public boolean isValid(Object[] value, ConstraintValidatorContext context) {
if (value.length != 2) {
throw new IllegalArgumentException("Illegal method signature");
}
if (value[0] == null || value[1] == null) {
return true;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.