And / Or condition in Spring annotation-based validation

I am using Spring 3 annotation based validation. I want to add the following check for string fields

The field can be Null OR , it must contain a non-empty string

I know an annotation like @Null , @NotEmpty , but how can I use both with an OR condition?


Decision:

Using @Size(min=1) helps, but does not handle spaces. Therefore, a custom NotBlankOrNull annotation has been NotBlankOrNull , which will allow null and non-empty lines to also take care of empty spaces. Thanks a lot @Ralph.
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 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) { } } 

I also updated it on the site .

+7
source share
1 answer

First of all, this is not a Spring annotation-based check, it is a JSR 303 Bean Validation implemented, for example, using Hibernate Validation. This is really not Spring related /

You cannot combine annotations along the OR path.

But there is a simple workaround for a non-zero constraint, since the most basic checks take null as valid input (so you often need to combine the basic options and optional @NotNull if you want to have "normal" "behavior, but not about than you asked).

For example: @javax.validation.constraints.Size accept null as valid input.

So you need to use @Size(min=1) instead of @NotEmpty in your case.

BTW: Not @NotEmpty - it's just a combination of @NotNull and @Size(min = 1)

* except that you implement it yourself.

+5
source

All Articles