Variable based javax bean validation?
•
Java
Suppose I have a class with two member variables:
import javax.validation.constraints.Min; class Foo { private int minimumAge; private int maximumAge; }
I know I can verify min / max like this:
@Min(1) private int minimumAge; @Max(99) private int maximumAge;
But what I really want to do is make sure that minimumage is always less than or equal to maximumage So I want something like this:
@Min(1) @Max(maximumAge) private int minimumAge; @Min(minumumAge) @Max(99) private int maximumAge;
But this verification framework seems impossible because it can only use constant expressions Is there any way to do such a thing?
thank you!
Solution
As Zack said, you can use custom constraints
With hibernate validator, you can use @ scriptasset constraint, which allows you to define constraints using any JSR 223 compatible script engine:
@ScriptAssert(lang = "javascript",script = "_this.minimumAge < _this.maximumAge") public class MyBean { @Min(1) private int minimumAge; @Max(99) private int maximumAge; }
If you really need to declare constraints dynamically, you can use hibernate validator's API for programming constraint definition:
int dynamicallyCalculatedConstraintValue = ...; ConstraintMapping mapping = new ConstraintMapping(); mapping.type( MyBean.class ) .property( "mininumAge",FIELD ) .constraint( new MaxDef().value( dynamicallyCalculatedConstraintValue ) ); HibernateValidatorConfiguration config = Validation.byProvider( HibernateValidator.class ).configure(); config.addMapping( mapping ); Validator validator = config.buildValidatorFactory().getValidator();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码