简体   繁体   English

可空的Datetime对象自定义数据注释验证

[英]Nullable Datetime object custom data annotation validation

I have a view model with 3 DateTime properties. 我有一个具有3 DateTime属性的视图模型。 StartDate EndDate ValueDate StartDate EndDate ValueDate

All the date properties are optional except the EndDate. 除EndDate外,所有日期属性都是可选的。 I have added a validation Attribute to the properties. 我已经向属性添加了一个验证属性。 My issue is when I call the IsValid(object value) method, the value parameter comes back with a default even if there is no data passed to the object. 我的问题是,当我调用IsValid(object value)方法时,即使没有数据传递给对象,value参数也会返回默认值。

How do I Validate a nullable DateTime object if Im expecting it's value to be null and the property is defaulting to a system default date. 如果我期望它的值为空并且属性默认为系统默认日期,那么如何验证可为空的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
}
}

What I am trying to achieve he is: There is a minim mum date that is selectable, The minimum date is stored in the application settings (Properties.Settings). 我要达到的目的是:有一个最小的最小日期可以选择,最小的日期存储在应用程序设置(Properties.Settings)中。 When ever the StartDate is set, then I dont want to apply the minimum date validation on the ValueDate, vice versa. 无论何时设置StartDate,我都不想在ValueDate上应用最小日期验证,反之亦然。 The user interface allows on one of the two(StartDate and ValueDate) to be selected. 用户界面允许选择两个(StartDate和ValueDate)之一。 If one is slecetd then the other is set to null and on the web (DataAnnotation) I only want to validate a DateTime? 如果一个被选中,则另一个被设置为null并在网络上(DataAnnotation)我只想验证DateTime? property that has a value. 具有值的属性。

When you instantiate your model, it may be worth trying setting the Nullable date fields to a NULL value. 实例化模型时,可能值得尝试将Nullable date字段设置为NULL值。 Eg 例如

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

}

Once done, you can then use the .HasValue() method to test it for a value: 完成后,您可以使用.HasValue()方法测试它的值:

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

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

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