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 { };
}
验证器类
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屋!