清单中的Java验证 [英] Java validation from list
问题描述
如果我有一个类,并且想检查该类中某个属性的输入是否在列表中,我该怎么做?
If I have a class and I want to check if the input to a property in that class is in a list, how would I do this?
示例
public class Length {
public static final List<String> ALLOWABLE_UNITS =
Collections.unmodifiableList(Arrays.asList("inches", "feet", "meters", "millimeters"));
public BigDecimal lengthValue;
@SomeMatchingAnnotation(ALLOWABLE_UNITS)
public String lengthUnit;
}
是否有注释可以做到这一点?我需要创建自己的吗?
Is there an annotation to do that? Would I have to create my own?
推荐答案
如果您正在使用JSR-303来验证bean,则可以查找一些自定义验证,编写自己的验证,或者仅使用javax.validation.constraints.Pattern
:>
If you are using JSR-303 to validate your beans then you can look for some custom validations, write yourself one, or just use javax.validation.constraints.Pattern
:
@Pattern(message="your message here" , regexp="^(meter|inch|cm)$")
public String lengthUnit;
更新
如果您要传递动态构建的正确值数组,则应该使用自定义验证.如果将Hibernate Validator
用作JSR-303提供程序,则可以使用@ScriptAssert
批注,该批注允许您使用兼容JSR-223的脚本引擎来定义约束:
If you want to pass dynamically built array of correct values then you should rather use custom validation. If you use Hibernate Validator
as JSR-303 provider then you can alternatively use the @ScriptAssert
annotation which allows you to define constraints using JSR-223 compatible scripting engine:
@ScriptAssert(lang = "javascript", script = "_this.possibleValues.indexOf(_this.lengthUnit) > -1")
请注意,我没有在上面的示例中运行,但是它应该可以正常工作.
Please note that I did not run above example, but it should work as expected.
或者,您可以在运行中添加约束(仍然假设您使用了休眠验证).
Alternatively you can add constraint in on-the-fly mode (still assuming that you use Hibernate Validation).
ConstraintMapping customMapping = new ConstraintMapping();
customMapping.type(Length.class).property("lengthUnit", FIELD).constraint(new PatternDef().regexp("^(mm|cm|inch)$"));
HibernateValidatorConfiguration cfg = Validation.byProvider(HibernateValidator.class).configure();
cfg.addMapping(customMapping);
ValidatorFactory vf = cfg.buildValidatorFactory();
Validator validator = vf.getValidator()
这篇关于清单中的Java验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!