dharam
dharam

Reputation: 8096

Spring Validation

I am trying to use something of this sort in my Command Object for Spring.

    @NotBlank
private String carrier;

@NotBlank(applyIf = "this.carrier EQUALS 'GlobalCrossing'")
    private String port;

Please let me know, if this is possible. The field carrier can have many values, If the value is GlobalCrossing then a not blank check should be applied on port field.

Can I do this with spring validation modules or there is another way of achieving the same?

Upvotes: 0

Views: 438

Answers (2)

janine
janine

Reputation: 11

Since you can annotate also methods you can try this.

 import javax.validation.constraints.*;

 .
 .
 .
  @AssertTrue
  private boolean isPortNotBlankIfCarrierEqualsGlobalCrossing() {
        return carrier.compareTo("GlobalCrossing") == 0 ? port.isBank() : true; 
  }

Upvotes: 0

DwB
DwB

Reputation: 38300

Since your validation is order dependent (i.e. carrier must be set before port) you might want to perform your validation post initialization.

In Spring, you can do any of these to create an initialization callback method:

  1. Implement the org.springframework.beans.factory.InitializingBean interface.
  2. Declare an initialization method with the init-method attribute (of the bean tag).
  3. Declare a default initialization method for your beans with the default-init-method attribute (of the beans tag).

However you do it, you can then perform the validation in the initialization callback method. Here is a link to the reference for initialization callbacks.

Upvotes: 1

Related Questions