Reputation: 22710
I am using Spring 3 annotation based validation. I want to add a following validation for String fields
Field can be Null OR it should contain a non empty string
I know annotation like @Null
, @NotEmpty
but how I can use both with a OR condition?
Solution:
Using @Size(min=1)
helps but it don't handle spaces. So added a custom annotation NotBlankOrNull
which will allow null
and non empty strings also it takes care of blank 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 have also updated it on my site.
Upvotes: 8
Views: 4541
Reputation: 120791
First of all, it is not Spring annotation based validation, it is JSR 303 Bean Validation, implemented for example by Hibernate Validation. It is really not spring related/
You can not combine the annotations in an OR way*.
But there is a simple workaround for the not null constraint, because the most basic validations accept null as an valid input (therefore you often need to combine the basic vaidations and an extra @NotNull, if you want to have a "normal" behavior but not what you asked for).
For Example:
@javax.validation.constraints.Size
accept null as an valid input.
So what you need in your case is use @Size(min=1)
instead of @NotEmpty
.
BTW: Not @NotEmpty
is just an combination of @NotNull
and @Size(min = 1)
*except you implement it by your self.
Upvotes: 5