JSR-303 Bean Validation for enum fields
bean-validation, jakarta-ee, java-ee-6
Solution
If you want to put the constraint on testField you need a custom validator. None of the default ones handle enums.
As a workaround you could add a getter method which returns the string value of the enum
public class TestBean{
private TestEnum testField;
//getters + setters
@Pattern(regexp = "A|B") //does not work
private String getTestFieldName() {
return testField.name();
}
}
A custom validator is probably the cleaner solution though.
Problem
I have a simple bean with `enum` field ``` public class TestBean{ @Pattern(regexp = "A|B") //does not work private TestEnum testField; //getters + setters } enum TestEnum{ A, B, C, D } ``` I would like to validate `testField` using Bean Validation. Specifically I would like to make sure that only A and B values are allowed (for a particular calidation gropus). It seems that enums are not handled JSR 303 (I was trying to use @Pattern validator) or I am doing something in a wrong way. I am getting exception: ``` javax.validation.UnexpectedTypeException: No validator could be found for type: packagename.TestEnum ``` Is there any way to validate enum fields without writing custom validator?