0

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 {
   /* ... */
}

1 Answer 1

2

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 {
   /* ... */
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.