【问题标题】:Nullable Datetime object custom data annotation validation可空日期时间对象自定义数据注释验证
【发布时间】:2015-07-03 04:48:08
【问题描述】:

我有一个具有 3 个 DateTime 属性的视图模型。 开始日期 结束日期 值日

除 EndDate 外,所有日期属性都是可选的。 我在属性中添加了一个验证属性。 我的问题是当我调用 IsValid(object value) 方法时,即使没有数据传递给对象,value 参数也会返回默认值。

如果我期望它的值为 null 并且属性默认为系统默认日期,我如何验证可为空的 DateTime 对象。

public class TestClass
{
[CusomValidator]
public DateTime? StartDate {get;set;}
[CusomValidator]
public DateTime? EndDate {get;set;}
[CusomValidator]
public DateTime? ValueDate {get;set;}
}

public class CusomValidator: ValidationAttribute
{
public bool IsValida(object value)
{
 //At this point value has the default system DateTime
 // When I post the model, the properties which are suppose to be null are null and that is what I want
}
}

我想要达到的目标是: 有一个可选择的最短日期,最短日期存储在应用程序设置 (Properties.Settings) 中。设置 StartDate 时,我不想在 ValueDate 上应用最小日期验证,反之亦然。用户界面允许选择两者之一(StartDate 和 ValueDate)。如果一个是 slecetd 然后另一个设置为 null 并且在网络上(DataAnnotation)我只想验证一个 DateTime?有值的属性。

【问题讨论】:

  • 请在您的模型中至少显示这三个属性。
  • 它实际上是一个可以为空的日期时间吗? (即DateTime? 而不是DateTime。)
  • EBrown,请看更新,是DateTIme?
  • @CodeNoob 你试过使用属性 [DefaultValue null] 吗?
  • 是的,我确实尝试过,但没有成功。

标签: c# asp.net-mvc-3 data-annotations


【解决方案1】:

当您实例化您的模型时,可能值得尝试将 Nullable 日期字段设置为 NULL 值。例如

public class MyModel
{
  [Required]
  public DateTime EndDate {get; set;}
  public Nullable<DateTime> StartDate {get; set;}
  public Nullable<DateTime> ValueDate {get; set;}

}

完成后,您可以使用 .HasValue() 方法对其值进行测试:

if (!valueDate.HasValue)
 {
     //unassigned
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多