How to validate 2 field with OR condition?

10,557

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;
}
Share:
10,557
praveen jain
Author by

praveen jain

Updated on June 14, 2022

Comments

  • praveen jain
    praveen jain almost 2 years

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