Spring中的条件验证 [英] Conditional validations in Spring
问题描述
我有一个包含一些radio
按钮和check-boxes
的表格.每当用户选择/取消选择radio button
或check-box
时,都会启用/禁用其他几个输入字段.
我只想为用户提交表单时启用的字段添加验证.提交时禁用的字段不应考虑进行验证.
I have a form which contain some radio
button and check-boxes
. Whenever user selects/deselects a radio button
or check-box
few other input fields are enabled/disabled.
I want to add validation only for fields which are enabled when user submits the form. Fields which are disabled at the time of submission should not be considered for validation.
我不想在客户端验证中添加它.是否有更好的/简便的方法在Spring 3.0中实现条件验证,而不是在验证器中添加多个if
?
I don't want to add this in client side validation.Is there any better /easy way to implement conditional validation in Spring 3.0 instead of adding multiple if
in validator ?
谢谢!
推荐答案
禁用字段后,它们将作为null
传输到控制器.我想添加一个验证,该验证将允许null
即禁用字段或not blank
字段即启用但为空字段.
因此,我创建了一个自定义批注NotBlankOrNull
,该批注将允许null
和非空字符串,并且还可以保留空格.
这是我的注释
When fields are disabled they are transferred to controller as null
. I wanted to add a validation which will allow either null
i.e disabled field or not blank
field i.e. enabled but empty field.
So I created a custom annotation NotBlankOrNull
which will allow null
and non empty strings also it takes care of blank spaces.
Here is my Annotation
@Documented
@Constraint(validatedBy = { NotBlankOrNullValidator.class })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
public @interface NotBlankOrNull {
String message() default "{org.hibernate.validator.constraints.NotBlankOrNull.message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
Validator类
Validator class
public class NotBlankOrNullValidator implements ConstraintValidator<NotBlankOrNull, String> {
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
if ( s == null ) {
return true;
}
return s.trim().length() > 0;
}
@Override
public void initialize(NotBlankOrNull constraint) {
}
}
我还在我的网站.
这篇关于Spring中的条件验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!