FluentValidation 具有条件验证和实体属性的不同规则

问题描述 投票:0回答:0

我有一个实体:

public class BookDto {
    public string? Id { get; set; }
    public string? ExternalBookId { get; set; }
    public string? Name { get; set; }
    public string? Description { get; set; }
    public string? Cost { get; set; }
    public string? ExternalClientId { get; set; }
}
// Validators
public class CreateBookValidator : AbstractValidator<BookDto> {
    public CreateBookValidator() {
        RuleFor(x => x.Id).NotEmpty();
    }
}

public class CreateBookValidator : AbstractValidator<BookDto> {
    public CreateBookValidator() {
        RuleFor(x => x.Id)
            .Empty().Unless(x => !string.IsNullOrEmpty(x.ExternalBookId));
        
        RuleFor(x => x.ExternalBookId)
            .Empty().Unless(x => !string.IsNullOrEmpty(x.Id));
    }
}

我需要能够根据不同的逻辑验证

BookDto
。 比方说:我有一本书来自 API,另一本书来自 FILE,我想对它们进行验证,但具有不同的验证逻辑。 不需要复制数百个“相同”逻辑的文件,可以做到吗?

尝试在数据库中创建 json 模式,但需要处理的内容太多,而且并非所有内容都按预期工作。 例如:

{
  "$schema": "https://json-schema.org/schema",
  "type": "object",
  "properties": {
    "id": {
      "type": "string"
    },
    "externalBookId": {
      "type": "string",
      "minLength": 1
    },
    "name": {
      "type": "string",
      "minLength": 1
    },
    "description": {
      "type": "string"
    },
    "cost": {
      "type": "number"
    },
    "externalClientId": {
      "type": "string",
      "minLength": 1
    }
  },
  "anyOf": [ // this part not working
    {
      "if": {
        "properties": {
          "id": { "type": "string" }
        }
      },
      "then": {
        "required": ["id"],
        "not": { "required": ["externalBookId"] }
      }
    },
    {
      "if": {
        "properties": {
          "externalBookId": { "type": "string" }
        }
      },
      "then": {
        "required": ["externalBookId"],
        "not": { "required": ["id"] }
      }
    }
  ],
  "required": ["name", "externalClientId"]
}

这是我尝试使用它的方法:

public T? Validate(string jsonData) {
        string jsonSchema = File.ReadAllText("../Application/Book/book-schema.json");
        JSchema schema = JSchema.Parse(jsonSchema);
         JObject jObject = JObject.Parse(jsonData);
        
        if (!jObject.IsValid(schema, out IList<ValidationError> validationErrors)) {
            throw new JsonValidationException(validationErrors);
        }

        return jObject.ToObject<T>();
    }

我想将所有模式保留在数据库中并将它们加载到每种类型的实体上,以便能够验证不同类型的请求(即文件/API)。

有人可以建议如何解决我的问题吗?

c# fluentvalidation json-schema-validator
© www.soinside.com 2019 - 2024. All rights reserved.