I am using two validation annotations on a property in the bean:
@NotEmpty(message = "{name.required}")
@Pattern(regex = "^([A-Za-z0-9]{2,}(\\-[a-zA-Z0-9])?)$", message = "{invalid.name}")
private String name;
If i left the name empty, I got the two errors but I want only the first error message (if the first condition occurs show its error message then skip the second condition).
if the first condition occurs show its error message then skip the second condition
This can be done by creating Composite Constraint and annotating it with @ReportAsSingleViolation meta constraint.
UserName.java
@ReportAsSingleViolation
@NotEmpty
@Pattern(regexp="^([A-Za-z0-9]{2,}(\\-[a-zA-Z0-9])?)$")
@Constraint(validatedBy = {})
public @interface UserName {
String message() default "invalid userName!";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Reference 3.2. Constraint composition