我们可以根据请求参数向请求体添加验证吗

Can we add validation to the request body based on the request Parameter

我有一个 REST 端点,它接受请求正文中的一个对象和一个请求参数。传入请求参数时,我需要验证对象的所有属性,如果不是参数 采用分配的默认值,只需要验证 2 个属性。两种情况下的路径都必须相同。如何实现?

目前我检查对象的模式、长度和可能值,并在注释的帮助下进行验证。

----- 更新 Class ------

@ValidateParent(parent = "parent ", child= "child")
public class anClass{

    @NotNull(groups = {FrstValidator.class, SndValidator.class})
    @Pattern(regexp = "^[a-zA-Z]{3}$",
            groups = {FrstValidator.class, SndValidator.class})
    String str1;

    @NotNull(groups = {FrstValidator.class, SndValidator.class})
    @Pattern(regexp = "^[a-zA-Z]{3}$",
            groups = {FrstValidator.class, SndValidator.class})
    String str2;

    @Pattern(regexp = "^[a-zA-Z]{10}$",
            groups =  SndValidator.class)
    String child;

    @Pattern(regexp = "^[a-zA-Z]{10}$",
            groups = SndValidator.class)
    String parent;

    @Pattern(regexp = "^[a-zA-Z]{10}$",
            groups = SndValidator.class)
    String str3;


}

ValidateParent,检查在请求正文中传递子项时是否也传递了父项。

您可以使用验证组和两个单独的端点以优雅的“Spring 方式”实现您的目标,通过请求参数的存在来区分:

验证组:

// Validation groups are just marker interfaces
private interface PartialValidation {}
private interface FullValidation {}

请求 DTO:

@Data
private static class Request {
    // This field will be validated only for FullValidation validation group
    @NotNull(groups = FullValidation.class)
    String field1;
    // This field will be validated for both validation groups
    @NotNull(groups = {FullValidation.class, PartialValidation.class})
    String field2;
}

控制器:

// This endpoint is executed only if there is no myParam preprovided
@PostMapping(
    value = "/validation",
    params = "!myParam")
public void partialValidation(
    @RequestParam(defaultValue = "DEFAULT") String myParam,
    // Request is validated against the PartialValidation group
    @RequestBody @Validated(PartialValidation.class) Request request) {

    System.out.println("Partial validation");
}

// This endpoint is executed only if there is myParam preprovided
@PostMapping(
    value = "/validation",
    params = "myParam")
public void fullValidation(
    @RequestParam String myParam,
    // Request is validated against the FullValidation group
    @RequestBody @Validated(FullValidation.class) Request request) {

    System.out.println("Full validation");
}