Reputation: 2101
I am using JSR303 bean validation annotations in my JSF managed bean to validate text input. Here are the annotations:
@Size(min=0, max=20, message = "Value cannot be more than 20 characters")
@Pattern(regexp = "[^|]", message = "Invalid entry. See field description.")
private String txt;
The @Pattern
annotation throws an error when a pipe character is found in the string. But when a user leaves the field blank and clicks submit, the error is also thrown. Why is this happening when the field is blank?
Upvotes: 1
Views: 3719
Reputation: 28885
Because the regexp [^|]
needs exactly one character to match. You should use a quantifier: [^|]*
Here are some tests:
System.out.println(Pattern.matches("[^|]", "")); // false
System.out.println(Pattern.matches("[^|]", "a")); // true
System.out.println(Pattern.matches("[^|]", "aaa")); // false
System.out.println(Pattern.matches("[^|]*", "")); // true
System.out.println(Pattern.matches("[^|]*", "aaa")); // true
System.out.println(Pattern.matches("[^|]*", "a|a")); // false
Upvotes: 4