枚举字段的JSR-303 Bean验证 [英] JSR-303 Bean Validation for enum fields
问题描述
我有一个简单的bean,枚举
字段
公共类TestBean {
@Pattern(regexp =A | B)//不起作用
private TestEnum testField;
// getters + setters
}
enum TestEnum {
A,B,C,D
}
我想使用Bean Validation验证 testField
。具体来说,我想确保只允许A和B值(对于特定的calidation gropus)。似乎枚举没有处理JSR 303(我试图使用@Pattern验证器)或者我正在以错误的方式做某事。
我得到例外:
javax.validation.UnexpectedTypeException:找不到类型的验证器:packagename.TestEnum
有没有办法在不编写自定义验证器的情况下验证枚举字段?
如果要将约束放在 testField 上,则需要自定义验证器。没有默认值处理枚举。
作为一种解决方法,您可以添加一个getter方法,该方法返回枚举的字符串值
public class TestBean {
private TestEnum testField;
// getters + setters
@Pattern(regexp =A | B)//不起作用
private String getTestFieldName(){
return testField。名称();
}
}
自定义验证器可能是更清晰的解决方案。 / p>
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?
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.
这篇关于枚举字段的JSR-303 Bean验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!