How to conditionally invoke spring validators

nilesh

I have a model like below. Existing code already has validations on individual properties. Now I have a requirement to ignore existing validations on billing_country and address if buyer.method is foo. I was thinking I could have a custom validator at buyer level, check for method and invoke validations only when buyer.method!=foo. Is this a valid approach? Are there any better alternatives?

"buyer": {
    "method": "foo",
    "instruments": [
      {
        "card": {
          "type": "MASTERCARD",
          "number": "234234234234234",
          "expire_month": "12",
          "expire_year": "2017",
          "billing_country" : "US"
          "Address" : {
             "line1": "summer st",
             "city": "Boston"
             "country": "US"
           }
        }
      }
    ]
}
beerbajay

There's two ways to do this.

You can either

  1. create a custom validation annotation and validator which checks the value of method and then applies to appropriate validations to the other fields

  2. use validation groups, where you manually check the value of method, then choose which group to use; your annotated fields will then need to be changed to only be applied when that group is active.

Option #1

Define a class-level annotation:

@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = { MethodAndInstrumentsValidator.class })
@Documented
public @interface ValidMethodAndInstruments {
    String message() default "{my.package.MethodAndInstruments.message}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

Define a validator:

public class MethodAndInstrumentsValidator 
             implements ConstraintValidator<ValidMethodAndInstruments, Buyer> {
    public final void initialize(final ValidMethodAndInstruments annotation) {
        // setup
    }

    public final boolean isValid(final Buyer value, 
                                 final ConstraintValidatorContext context) {
        // validation logic
        if(!"foo".equals(value.getMethod())) {
            // do whatever conditional validation you want
        }
    }

}

Annotate the buyer class:

@ValidMethodAndInstruments
public class Buyer { }

Option #2

Here, you'll have to invoke the validation manually.

First, define the validation groups:

public interface FooValidation {}
public interface NotFooValidation {}

Configure a validator:

@Bean
public LocalValidatorFactoryBean validatorFactory() {
    return new LocalValidatorFactoryBean();
}

In your controller(?), check the value of method and do the validation:

@Autowired
private Validator validator;

// ...

public void validate(Object a, Class<?>... groups) {
    Set<ConstraintViolation<Object>> violations = validator.validate(a, groups);
    if(!violations.isEmpty()) {
        throw new ConstraintViolationException(violations);
    }
}

// ...

validate(buyer, "foo".equals(buyer.getMethod()) 
                    ? FooValidation.class 
                    : NotFooValidation.class);

Finally, modify the groups in your model/dto class:

public class Buyer {
    // ...

    @Null(groups = FooValidation.class)
    @NotNull(groups = NotFooValidation.class)
    protected String billingCountry;
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Angular: How to conditionally apply Validators for Reactive forms

From Dev

How to conditionally invoke a task in sbt?

From Java

How to Autowire conditionally in spring boot?

From Dev

How to Autowire conditionally in spring boot?

From Dev

Spring MockMVC - How to mock custom validators running outside of controllers

From Dev

Spring MockMVC - How to mock custom validators running outside of controllers

From Dev

Spring MVC custom validators

From Java

How to conditionally enable or disable scheduled jobs in Spring?

From Dev

How to invoke a Spring Controller from Java Filter

From Dev

How to bind validators to TextFields in vaadin?

From Dev

How to add Validators in Vaadin 8?

From Dev

How to bind validators to TextFields in vaadin?

From Dev

How to register all validators generically

From Dev

Invoke f:viewAction conditionally based on f:viewParam

From Dev

SonarQube: Invoke method(s) only conditionally

From Dev

Sonar violation: Invoke method(s) only conditionally

From Dev

SonarQube: "Invoke method(s) only conditionally"

From Java

How to conditionally make a spring boot application terminate at start-up

From Dev

How to conditionally expose data in Spring Data REST projection?

From Dev

How to conditionally make a spring boot application terminate at start-up

From Dev

How to invoke Spring STOMP web socket method from rest client

From Dev

How to invoke a controller using a html link in Spring-mvc?

From Dev

Spring ApplicationListener for ContextRefreshEvent. How to invoke only once per Hierarchy?

From Dev

How to invoke sftp:outbound-gateway from spring batch?

From Dev

How to invoke async controller logic after returning response using Spring?

From Dev

How to invoke a controller using a html link in Spring-mvc?

From Dev

How to invoke sftp:outbound-gateway from spring batch?

From Dev

How to invoke async controller logic after returning response using Spring?

From Dev

Spring Boot @EnableScheduling conditionally

Related Related

  1. 1

    Angular: How to conditionally apply Validators for Reactive forms

  2. 2

    How to conditionally invoke a task in sbt?

  3. 3

    How to Autowire conditionally in spring boot?

  4. 4

    How to Autowire conditionally in spring boot?

  5. 5

    Spring MockMVC - How to mock custom validators running outside of controllers

  6. 6

    Spring MockMVC - How to mock custom validators running outside of controllers

  7. 7

    Spring MVC custom validators

  8. 8

    How to conditionally enable or disable scheduled jobs in Spring?

  9. 9

    How to invoke a Spring Controller from Java Filter

  10. 10

    How to bind validators to TextFields in vaadin?

  11. 11

    How to add Validators in Vaadin 8?

  12. 12

    How to bind validators to TextFields in vaadin?

  13. 13

    How to register all validators generically

  14. 14

    Invoke f:viewAction conditionally based on f:viewParam

  15. 15

    SonarQube: Invoke method(s) only conditionally

  16. 16

    Sonar violation: Invoke method(s) only conditionally

  17. 17

    SonarQube: "Invoke method(s) only conditionally"

  18. 18

    How to conditionally make a spring boot application terminate at start-up

  19. 19

    How to conditionally expose data in Spring Data REST projection?

  20. 20

    How to conditionally make a spring boot application terminate at start-up

  21. 21

    How to invoke Spring STOMP web socket method from rest client

  22. 22

    How to invoke a controller using a html link in Spring-mvc?

  23. 23

    Spring ApplicationListener for ContextRefreshEvent. How to invoke only once per Hierarchy?

  24. 24

    How to invoke sftp:outbound-gateway from spring batch?

  25. 25

    How to invoke async controller logic after returning response using Spring?

  26. 26

    How to invoke a controller using a html link in Spring-mvc?

  27. 27

    How to invoke sftp:outbound-gateway from spring batch?

  28. 28

    How to invoke async controller logic after returning response using Spring?

  29. 29

    Spring Boot @EnableScheduling conditionally

HotTag

Archive