Spring中的条件验证

xyz*_*xyz 6 validation spring conditional

我有一个包含一些radio按钮的表单check-boxes.每当用户选择/取消选择一个radio buttoncheck-box几个其他输入字段被启用/禁用时.
我想仅为用户提交表单时启用的字段添加验证.提交时禁用的字段不应被视为验证.

我不想在客户端验证中添加它.有没有更好/更简单的方法在Spring 3.0中实现条件验证而不是if在验证器中添加多个?

谢谢!

Ral*_*lph 8

如果您使用JSR 303 Bean验证,那么您可以使用验证组(groups).

假设您有此用户输入,包含两个部分.两个布尔值表示部分是启用还是禁用.(当然你可以使用更多有用的注释@NotNull)

public class UserInput {
   boolean sectionAEnabled;
   boolean sectionBEnabled;

   @NotNull(groups=SectionA.class)
   String someSectionAInput;

   @NotNull(groups=SectionA.class)
   String someOtherSectionAInput;

   @NotNull(groups=SectionB.class)
   String someSectionBInput;

   Getter and Setter
}
Run Code Online (Sandbox Code Playgroud)

组需要两个接口.它们只作为标记.

public interface SectionA{}

public interface SectionB{}
Run Code Online (Sandbox Code Playgroud)

从Spring 3.1开始, 您可以在控制器方法中使用Spring@Validated注释(而不是@Validate)来触发验证:

@RequestMapping...
public void controllerMethod(
         @Validated({SectionGroupA.class}) UserInput userInput, 
         BindingResult binding, ...){...}
Run Code Online (Sandbox Code Playgroud)

春季3.1之前,有没有办法来指定应该被用于验证(因为验证组@Validated不存在,@Validate没有一组属性),所以你需要通过手工编写代码来开始验证:这一个例子如何在Spring 3.0中启用了依赖于女巫部分的验证.

@RequestMapping...
public void controllerMethod(UserInput userInput,...){

  ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
  Validator validator = factory.getValidator();

  List<Class<?>> groups = new ArrayList<Class<?>>();
  groups.add(javax.validation.groups.Default.class); //Always validate default
  if (userInput.isSectionAEnabled) {
     groups.add(SectionA.class);
  }
  if (userInput.isSectionBEnabled) {
     groups.add(SectionB.class);
  }
  Set<ConstraintViolation<UserInput>> validationResult =
     validator.validate(userInput,  groups.toArray(new Class[0]));

  if(validationResult.isEmpty()) {
     ...
  } else {
     ...
  }
}
Run Code Online (Sandbox Code Playgroud)

(顺便说一句:对于Spring 3.0解决方案,也可以让Spring注入验证器:

@Inject javax.validation.Validator validator

<mvc:annotation-driven validator="validator"/>

<bean id="validator"
      class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
       <property name="validationMessageSource" ref="messageSource" />
</bean>
Run Code Online (Sandbox Code Playgroud)

)


xyz*_*xyz 5

当字段被禁用时,它们将作为 传输到控制器null。我想添加一个验证,它将允许null即禁用字段或not blank字段即启用但空字段。
所以我创建了一个自定义注释NotBlankOrNull,它允许null和非空字符串也处理空格。
这是我的注释

@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 { };
}
Run Code Online (Sandbox Code Playgroud)

验证器类

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) {

    }
} 
Run Code Online (Sandbox Code Playgroud)

我还在我的网站上更新了更多详细信息。