JSR-303 Bean Validation for enum fields

前端 未结 3 672
南笙
南笙 2021-02-05 19:40

I have a simple bean with enum field

public class TestBean{
   @Pattern(regexp = \"A|B\") //does not work
   private TestEnum testField;
   //getter         


        
3条回答
  •  时光取名叫无心
    2021-02-05 20:04

    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.

提交回复
热议问题