【问题标题】:FluentValidation - Check value is a date only if NOT NULLFluentValidation - 仅当 NOT NULL 时检查值才是日期
【发布时间】:2013-05-25 06:45:26
【问题描述】:

我有一个布尔值和一个可为空的 DateTime 属性。 仅当 bool 设置为 true 时才需要 DateTime... 如果布尔为真,我想验证日期。

到目前为止我有这个表达......

When(p => p.HasVisa == true, () => RuleFor(p => p.VisaExpiryDate).NotNull());

现在我尝试使用 .Must 扩展名和我的自定义 BeAValidDate 方法验证该表达式中的日期...

When(p => p.HasVisa == true, () => RuleFor(p => p.VisaExpiryDate).NotNull().Must(BeAValidDate));

private bool BeAValidDate(DateTime date)
{
  if (date == default(DateTime))
    return false;
  return true;
}

但 .Must 扩展名不允许我对可为空的 DateTime 进行操作。 如何在可为空的日期进行此类验证?

谢谢

【问题讨论】:

  • 我从来没有使用过 FluentValidation,但你的问题不就是你的BeAValidDate 没有将DateTime?(即可以为空的日期时间)作为参数吗?
  • 哈哈,谢谢 Joachim,我想太多了,是的,你是对的。

标签: datetime fluentvalidation


【解决方案1】:

只需添加'When'来检查对象是否不为空:

RuleFor(x => x.AlternateNumber)
    .Must(IsAllDigits)
    .When(x => !string.IsNullOrEmpty(x.AlternateNumber))
    .WithMessage("AlternateNumber should contain only digits");

【讨论】:

  • 我知道情况并非如此,但是对于那些需要设置更多规则的情况,您可以使用 DependentRules 方法
【解决方案2】:

正如 Joachim 所说,我需要对 BeAValidDate 进行重载,以接受空日期和非空日期。

private bool BeAValidDate(DateTime date)
{
  if (date == default(DateTime))
    return false;
  return true;
}

private bool BeAValidDate(DateTime? date)
{
  if (date == default(DateTime))
    return false;
  return true;
}

【讨论】:

    【解决方案3】:

    这对我有用:

    RuleFor(user => user.DateOfBirth)
      .Must(p=> !(p == DateTime.MinValue))
      .WithMessage("DateTime not null");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 1970-01-01
      • 2021-01-18
      • 2012-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多