简体   繁体   English

验证参数是否等于给定条件之一 - 给定的可空输入。 null 也是有效条件

[英]Validate if parameter is equal to one of the given conditions - nullable input given. The null is a valid condition too

I'm trying to validate/check if the parameter x.Size is equal to one of the given conditions above.我正在尝试验证/检查参数x.Size是否等于上述给定条件之一。

The issue is that Size is string[]?问题是Sizestring[]? and conditions.Contains(x);conditions.Contains(x); expects x to be non nullable string.期望 x 是不可为 null 的字符串。 By the way, if Size is null, should be a valid condition too.顺便说一下,如果Size是 null,应该也是有效条件。

public string[]? Size { get; }

public sealed class GetProductsQueryValidator : AbstractValidator<GetProductsQuery>
{
    public GetProductsQueryValidator()
    {
        var conditions = new List<string> { "m", "l", "s" };

        RuleFor(x => x.Size)
            .Must(x => conditions.Contains(x)) // compile-time error: x is expected to be non nullable
            .WithMessage($"Please only use: {string.Join(",", conditions)}");
    }
}

You can use .When for this:您可以使用.When为此:

RuleFor(x => x.Size)
    .ForEach(i => i
        .Must(iv => conditions.Contains(iv!))
        .WithMessage($"Please only use: {string.Join(",", conditions)}")
        .When(iv => iv != null)
    )
    .When(x => x.Size != null);

Note that we need to apply a condition for each array item using ForEach .请注意,我们需要使用ForEach为每个数组项应用条件。

That way it will only evaluate the condition when Size isn't null, and only evaluates the item condition when the item isn't null.这样它只会在 Size 不是 null 时评估条件,并且只会在项目不是 null 时评估项目条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM