2

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 '&'?
1
  • Just a nitpick, you can reduce that regexp to ^\w+$. Commented Mar 17, 2014 at 18:11

1 Answer 1

1

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

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.