Galen
Galen

Reputation: 491

javax Bean Validation based on variables?

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 I can validate minimum / maximum values like this:

@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 does not seem possible with this validation framework, since it only can take constant expressions. Is there a way to do something like this?

Thanks!

Upvotes: 4

Views: 5411

Answers (3)

Zack Macomber
Zack Macomber

Reputation: 6905

Sounds like you may have to create a custom constraint.

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

Upvotes: 0

Galen
Galen

Reputation: 491

This is also something a friend told me, which I think may be even simpler than the @ScriptAssert approach:

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

Upvotes: -1

Gunnar
Gunnar

Reputation: 18990

As Zack said you could use a custom constraint.

With Hibernate Validator you could alternatively work with the @ScriptAssert constraint which allows to define constraints 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 could use Hibernate Validator's API for programmatic 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();

Upvotes: 2

Related Questions