Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate 2 field with OR condition?

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

like image 323
praveen jain Avatar asked Mar 25 '15 07:03

praveen jain


1 Answers

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;
}
like image 53
Mithun Avatar answered Oct 26 '22 04:10

Mithun