0

Using java validation is it possible to add constrains for a string property like it should have only some set of values. (for ex : AA,BB,CC,DD). I know I can use something like below, but it does not stop some junk values apart from my expected values.

The below code, allow me junk/unexpected values

@Size(min=2, max=2,message="")
@pattern("regex patter to allow string only)
private String prop;
6
  • 1
    For a set of values with defined possible values, use an enum Commented Dec 11, 2018 at 6:05
  • Whose implementation of the Bean Validation API are you using? Hibernate? Commented Dec 11, 2018 at 6:07
  • validation-api-2.0.1-Final Commented Dec 11, 2018 at 6:10
  • Seems like a duplicate of stackoverflow.com/questions/17481029/… Commented Dec 11, 2018 at 6:11
  • No, it was accepting all a-z string Commented Dec 11, 2018 at 6:13

1 Answer 1

3
@Pattern(regexp = "word1|word2|word3")
String name;

If you need more elaborated regexp use the one you need in the usual way.

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.