在我的场景中,我正在尝试创建注释,以验证一个字段是否已填充,如果另一个字段具有某种值。
界面如下所示:
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = RequiredIfFieldHasValueValidator.class)
public @interface RequiredIfFieldHasValue
{
String message() default "Required if selected";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
/*
FieldName against which we validate
*/
String fieldName() default "";
/*
Field value that indicates requirement
*/
String fieldValue() default "";
}
和实施:
public class RequiredIfFieldHasValueValidator implements ConstraintValidator<RequiredIfFieldHasValue, String>
{
private String fieldName;
private String fieldValue;
@Override
public void initialize( RequiredIfFieldHasValue constraintAnnotation )
{
fieldName = constraintAnnotation.fieldName();
fieldValue = constraintAnnotation.fieldValue();
validateParameters();
}
@Override
public boolean isValid( String value, ConstraintValidatorContext context )
{
System.out.println( "Validate against fieldname: " + fieldName + " fieldvalue: " + fieldValue );
//
//Validation should be here (1)
//
return false;
}
private void validateParameters()
{
if ( "".equals( fieldName ) || fieldName == null )
{
throw new IllegalArgumentException( "The fieldname cannot be null" );
}
}
}
以及示例用法:
public class Form {
private String type;
@RequiredIfFieldHasValue(fieldName = "type", fieldValue = "DICT")
private String dictValue;
}
我在 Spring MVC 中使用它并根据请求进行验证,如下所示:
public String myFormPostPost( Model model, @Valid @ModelAttribute MyForm form, indingResult result )
所以我的目标是:If field type has value equal to DICT, field dictValue should be required (not empty)
.
我的问题是我是否可以访问当前的 bean 值Validation should be here (1)
?我知道我可以对整个 bean 进行注释,但我更喜欢这样。