Search code examples
javaregexvalidationjava-8javabeans

Java bean validation uppercase letters with range


I have a some issue with pattern for java bean validation. I have a pattern for my variable inside java class

@Pattern(regexp = ".*[A-Z]+[[A-Z]\\p{Space}]+[A-Z\\p{Punct}]+([0-9]{1,10})?", message = "Error")*
private String name;

And actually it's working, but now I have to add a range {0,32} to uppercase words. When I added [A-Z]{0,32} it breaks down

The name should fit values below

  1. PROFILE - true
  2. P - true
  3. PRO - true
  4. PROFILEPROFILEPROFILEPROFILEPROF - true
  5. PROFILEPROFILEPROFILEPROFILEPROFI - false
  6. profilename - false
  7. PROFILE1 - true
  8. PROFILE100 - true
  9. PROFILE1000 - true
  10. PROFILE1000000 - true
  11. 1111 - false
  12. PROFILEPROFILE123456789PROFILE123 - false
  13. profile_name - false
  14. *^^@ - false
  15. PROFILE NAME - true
  16. PROFILE_NAME - true
  17. PROFILE. - true
  18. &)12p - false
  19. 11PROFILE - true
  20. 1234PROFILE - true
  21. $%#PROFILE - true
  22. nothing - false

How to change/refactor that pattern to possible to add range for uppercase letter and 2, 5, 12 would working?

The solution is "(?=.*[A-Z])[\p{Punct}A-Z0-9 ]{1,32}"


Solution

  • You may use

    @Pattern(regexp = "(?=.*[A-Z])[\\p{Punct}A-Z0-9 ]{1,32}", message = "Error")
    

    See the regex demo

    Since the pattern is anchored by default (it is used with .matches() method), no ^ and $ are necessary around the pattern.

    It matches:

    • (?=.*[A-Z]) - after any 0+ chars other than linebreak chars there must be at least 1 uppercase ASCII letter
    • [\\p{Punct}A-Z0-9 ]{1,32} - match 1 to 32 uppercase ASCII letters, digits, space or chars from the Punct POSIX character class (it includes punctuation and symbols).