9

我想以一个字段有效或另一个字段有效的方式验证请求类的两个字段。

例如:请求 Bean

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

控制器方法

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

在这里,我想检查 customerName 应该是 NotEmpty 还是 customerId 应该是 NotEmpty。那么我的验证应该通过。我该如何实现它。请推荐!!

4

1 回答 1

20

您需要创建自定义验证器来验证多个字段。

创建自定义注释:

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

创建一个自定义验证器:

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

现在,使用自定义注释来注释您的模型:

@RequestAnnotation 
public class CarRequest  {
    private String customerName;
    private String customerId;
}
于 2015-03-25T08:25:18.187 回答