Maxim Kolesnikov
Maxim Kolesnikov

Reputation: 5145

Analogue of @NotRquired annotation for validation

I use Hibernate Validation 4.3.1.Final and Spring 3.2.0.RELEASE

I have a form with a string attribute. This attribute is not required, but if it contains some value this value should be exactly 10 digits length. So I need somthing like:

@NotRquired
@Length(min = 10, max = 10)

But there is no annotation like @NotRquired. How I should write validation for this case?

Upvotes: 0

Views: 111

Answers (1)

Hardy
Hardy

Reputation: 19129

Not that a @NotRquired annotation would not help in this case, because all defined constraints are evaluated. So in the case where the value is not specified @Length would still be validated and fail. There are several things you could do:\

  • Use the @Pattern constraint and define a pattern which matters the empty string and the one of length 10 characters. Provided of course for not required case you get an empty string
  • Write a custom constraint, for example @EmptyOrLength which does what you want
  • Try working with validation groups and assign each constraint to a different group. You then need a way to target the right validation group
  • Revert to Hibernate Validator specific functionality and use boolean composition of constraints - http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#d0e3701. You still need a custom constraint though, but you can use a composition of @NotNull and @Length using @ConstraintComposition(OR)

Upvotes: 1

Related Questions