How to validate 2 field with OR condition?

praveen jain picture praveen jain · Mar 25, 2015 · Viewed 9.3k times · Source

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!!

Answer

Mithun picture Mithun · Mar 25, 2015

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;
}