Reputation: 21081
In a system, I'm working in, the username
must be either email
or cell number
.
I'm using Hibernate Validator to validate the bean.
I want to create a custom annotation @Username
such that it validate a bean property to be either email
or a cell number
.
Email can be validated with @Email
and cell number with a regex using @Pattern
but I couldn't figure out how to write a custom validator such that I can reuse above built-in annotations.
I referred to Creating custom validator section to create custom validator.
Basically my question is,
How can I use built-in validation annotations (@Email
and @Pattern
) to compose a new annotation @Username
such that @Username
validate a property to be either email
or cell number
?
// @Email or @Pattern("...") ???
@Target(FIELD)
@Retention(RUNTIME)
@Constraint(validatedBy = {})
@Documented
public @interface Username {
/* ... */
}
Upvotes: 0
Views: 2878
Reputation: 19119
If you want to be Bean Validation compliant, you cannot. There is no concept of OR composition of constraints. However, if you are using Hibernate Validator and you are ok with provider specific features you can make use of boolean composition in Hibernate Validator - http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-boolean-constraint-composition
@Target(FIELD)
@Retention(RUNTIME)
@Constraint(validatedBy = {})
@Documented
@ConstraintComposition(OR)
@Email
@Pattern("...")
public @interface Username {
/* ... */
}
Upvotes: 2