I'm working with a HTML form that accepts 4 dates, two of which are optional. These dates are inserted into a MS SQL database, so I'm boundary checking the DateTime variables, which are passed from the form, against SqlDateTime.MinValue
and SqlDateTime.MaxValue
. Here's what my model looks like:
[Required]
[DisplayName("Planned Start Date")]
[CustomValidation(typeof(Goal), "ValidateGoalDate")]
public object planned_start_date { get; set; }
[DisplayName("Actual Start Date")]
[CustomValidation(typeof(Goal), "ValidateGoalDate")]
public object start_date { get; set; }
[Required]
[DisplayName("Planned End Date")]
[CustomValidation(typeof(Goal), "ValidateGoalDate")]
public object planned_end_date { get; set; }
[DisplayName("Actual Start Date")]
//[CustomValidation(typeof(Goal), "ValidateGoalDate")]
public object end_date { get; set; }
And my custom validator:
public static ValidationResult ValidateGoalDate(DateTime goalDate) {
//* this does not appear to work ever because the optional field does
//* not ever get validated.
if (goalDate == null || goalDate.Date == null)
return ValidationResult.Success;
if (goalDate.Date < (DateTime)SqlDateTime.MinValue)
return new ValidationResult("Date must be after " + SqlDateTime.MinValue.Value.ToShortDateString());
if (goalDate.Date > (DateTime)SqlDateTime.MaxValue)
return new ValidationResult("Date must be before " + SqlDateTime.MaxValue.Value.ToShortDateString() );
return ValidationResult.Success;
}
The problem occurs whenever you submit the form without the optional values. In my controller, my ModelState.IsValid returns false and I get a validation error message:
Could not convert the value of type 'null' to 'System.DateTime' as expected by method GoalManager.Models.Goal.ValidateGoalDate. Must enter a valid date.
Stepping though the code, I see that the custom validator does not run on the optional fields, but when I remove the DataAnnotation from those optional fields, I return no error. If the user does not insert a date into the field, I want to insert a NULL into the table. How do tell the Validator that I do not want to error check a blank (or null) date, to ignore it, and to insert a null into the database?
The DateTime that your custom validator takes as a param is not nullable in your example... If you make it a nullable DateTime, it should fix your problem.
Here's the implementation of what @Rikon said:
public static ValidationResult ValidateGoalDate(DateTime? goalDate) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With