【问题标题】:How to Use fluent validation for nullable string?如何对可空字符串使用流畅的验证?
【发布时间】:2021-08-13 13:53:48
【问题描述】:

我有下面的代码抛出空检查异常:

 RuleFor(x => x.TestString)
                .Must(x => !string.IsNullOrEmpty(x))
                .When(y => y.OtherArray!= null && y.OtherArray.Count > 0)
                .WithMessage("required") 
                .Must(x=> x.TestString.Equals("tiktok"))
                .WithMessage("Invalid") 

但是上面的代码在TestString为空时抛出了Object空引用异常。

我的要求是当“OtherArray”有值时,“TestString”必须等于“tiktok”,此时应显示无效的TestString Invalid错误消息。

当“OtherArray”为空或为空时,无需检查“TestString”。 有人可以帮忙吗?

【问题讨论】:

    标签: c# asp.net-core fluentvalidation fluentvalidation-2.0


    【解决方案1】:

    试试这个:

    RuleFor(x => x.TestString)
                .Must(x => !string.IsNullOrEmpty(x))
                .When(y => y.OtherArray!= null && y.OtherArray.Count > 0)
                .WithMessage("required") 
                .Must(x=> x.TestString != null && x.TestString.Equals("tiktok"))
                .WithMessage("Invalid") 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-23
      • 1970-01-01
      • 2021-05-20
      • 1970-01-01
      • 2016-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多