多个约束 spring 验证

Multiple constraints spring validation

我正在使用 spring 来验证表单。表单的模型类似于:

public class FormModel {

    @NotBlank
    private String name;

    @NotNull
    @ImageSizeConstraint
    private MultipartFile image;

}

“@ImageSizeConstraint”是自定义约束。我想要的是首先评估@NotNull,如果评估为假,则不评估@ImageSizeConstraint。

如果这不可能,我还必须检查自定义约束中的空值。这不是问题,但我想分开关注(不是空/图像大小/图像/纵横比/等)。

您可以使用约束分组和分组序列来定义验证顺序。根据JSR-303(部分3.5.验证例程):

Unless ordered by group sequences, groups can be validated in no particular order. This implies that the validation routine can be run for several groups in the same pass.

正如 Hibernate Validator documentation 所说:

In order to implement such a validation order you just need to define an interface and annotate it with @GroupSequence, defining the order in which the groups have to be validated (see Defining a group sequence). If at least one constraint fails in a sequenced group, none of the constraints of the following groups in the sequence get validated.

首先,您必须定义约束组并将它们应用于约束:

public interface CheckItFirst {}

public interface ThenCheckIt {}

public class FormModel {

    @NotBlank
    private String name;

    @NotNull(groups = CheckItFirst.class)
    @ImageSizeConstraint(groups = ThenCheckIt.class)
    private MultipartFile image;
}

然后,由于约束的评估没有特定顺序,无论它们属于哪个组(Default 组),您必须为您的 image 创建 @GroupSequence字段限制组。

@GroupSequence({ CheckItFirst.class, ThenCheckIt.class })
public interface OrderedChecks {}

您可以使用

进行测试
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<FormModel>> constraintViolations =
                            validator.validate(formModel, OrderedChecks.class);

要在 Spring MVC 控制器方法中应用此验证,您可以使用 @Validated 注释,它可以指定方法级验证的验证组:

@PostMapping(value = "/processFormModel")
public String processFormModel(@Validated(OrderedChecks.class) FormModel formModel) {
    <...>
}

如果图像对于您的自定义约束为 null,则 isValid 只需 return true 即可。 阅读 JSR-303 的规范,您会发现这是正常行为并且有道理,因为有 "NotNull".