Javax Bean Variable Based Validation?

Let's say I have a class with two member variables:

import javax.validation.constraints.Min; class Foo { private int minimumAge; private int maximumAge; } 

I know that I can state the min / max values ​​as follows:

 @Min(1) private int minimumAge; @Max(99) private int maximumAge; 

But what I really want to do is to ensure 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 is not possible with this validation card, since it can only accept constant expressions. Is there a way to do something like this?

Thanks!

+4
source share
3 answers

As Zach said, you can use a custom constraint.

Using the Hibernate Validator, you can alternatively work with @ScriptAssert , which allows you to define restrictions using any JSR 223-compatible scripting 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 in a dynamic way, you can use the Hibernate Validator API to define software constraints:

 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(); 
+2
source

It looks like you might have to create your own constraint.

http://java.dzone.com/articles/using-hibernate-validator has a good section on creating (or overloading) restrictions - "Individual restrictions and checks"

0
source

This is also what a friend told me, which, in my opinion, is even simpler than the @ScriptAssert approach:

@AssertTrue public boolean isValidAge() { return minAge < maxAge; }

-1
source

Source: https://habr.com/ru/post/1388640/


All Articles