0
votes

I have a view model with 3 DateTime properties. StartDate EndDate ValueDate

All the date properties are optional except the 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.

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.

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). When ever the StartDate is set, then I dont want to apply the minimum date validation on the ValueDate, vice versa. The user interface allows on one of the two(StartDate and ValueDate) to be selected. If one is slecetd then the other is set to null and on the web (DataAnnotation) I only want to validate a DateTime? property that has a value.

1
Please show at least those three properties in your Model. - krillgar
Is it actually a nullable DateTime? (I.e. DateTime? instead of DateTime.) - Der Kommissar
EBrown, please see update, it is DateTIme? - CodeNoob
@CodeNoob Have you tried using the attribute [DefaultValue null] ? - Paul Zahra
Yes I did try that and It did not work. - CodeNoob

1 Answers

1
votes

When you instantiate your model, it may be worth trying setting the Nullable date fields to a NULL value. E.g.

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:

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