【问题标题】:Fluent validation allow empty or value with structure流利的验证允许空或带有结构的值
【发布时间】:2021-12-09 19:20:54
【问题描述】:

我有一个排序道具,它可以是空的,也可以是类似的值:

sort=""
sort=["name","desc"]
sort=["name","asc"]


RuleFor(r => r.Sort)
                .NotEmpty()
                .When(nr => nr.Contains("name"))
                .WithMessage("Invalid Sort");

如何允许空的,非空的with包含一个字符串?

【问题讨论】:

  • r.Sort 使用的是什么类型?是string吗?是IEnumerable<string>吗?有什么不同?

标签: c# fluentvalidation


【解决方案1】:

您可以指定一个自定义规则。假设Sort 属于string[]

RuleFor(r => r.Sort)
    .NotNull()
    .Must(x => x.Length == 0 || (x.Length == 2 && x[0] == "name" && 
        (x[1] == "desc" || x[1] == "asc")))
    .WithMessage(...);

如果您需要重用此逻辑,只需使用自定义规则构建器as explained here

【讨论】:

    猜你喜欢
    • 2013-04-19
    • 1970-01-01
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    相关资源
    最近更新 更多