Search code examples
regexformsspringpattern-matchinghibernate-validator

Java Regex Matching And Hibernate Validators


I am using Hibernate validators on my form and am running into this problem. The validators are as follows:

@NotEmpty(message = "Firstname cannot be empty")
@Pattern(regexp = "^[a-zA-Z0-9_]+$", message = "First Name can only contain characters.")
private String firstname;

If the firstname is empty both @NotEmpty as well as @Pattern are getting triggered.

Question

  • How do I make @NotEmpty trigger ONLY when the firstname is empty and @Pattern trigger ONLY when it contains illegal characters like '#' or '&'?

Solution

  • Try:

     ^[a-zA-Z0-9_]*$
    

    Instead of:

     ^[a-zA-Z0-9_]+$
    

    The * should make your regex also match the empty String. So for the case the String is empty only @NotEmpty should be triggered