How to validate 2 field with OR condition?
Asked Answered
G

1

9

I want to validate two fields of a Request Class in manner that Either one field is valid OR another field is valid.

Eg: Request Bean

public class CarRequest  {
    @NotEmpty
    private String customerName;
    @NotEmpty
    private String customerId;

Controller Method

    public @ResponseBody CarResponse addCar(
            @ModelAttribute @Valid CarRequest request, BindingResult results)
            throws RuntimeException, ValidationException {
        if (results.hasErrors()) {
            LOG.error("error occured while adding the car");
            throw new ValidationException(
                    "Error Occoured while validiating car request");
        }
}

Here I want to check that either customerName should be NotEmpty OR customerId should be NotEmpty. then my validation should pass. How can I implement it . Please suggest!!

Garrow answered 25/3, 2015 at 7:47 Comment(2)
You need to write a custom validator for that and bind it to your model.Sensitivity
can you please provide some reference for same ?Garrow
G
25

You need to create custom validator to validate multiple fields.

create a custom annotation:

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Documented
@Constraint(validatedBy = CarRequestValidator.class)
@Target({ ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestAnnotation {
    String message() default "{RequestAnnotation}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

create a custom validator:

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class CarRequestValidator implements 
                ConstraintValidator<RequestAnnotation, CarRequest> {

    @Override
    public void initialize(RequestAnnotation constraintAnnotation) {

    }

    @Override
    public boolean isValid(CarRequest value, ConstraintValidatorContext context) {
        // validation logic goes here
        return false;
    }
}

Now, annotate your model with custom annotation:

@RequestAnnotation 
public class CarRequest  {
    private String customerName;
    private String customerId;
}
Geography answered 25/3, 2015 at 8:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.