Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataAnnotation and optional DateTime values

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?

like image 871
jungos Avatar asked Aug 05 '11 17:08

jungos


2 Answers

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.

like image 174
Rikon Avatar answered Nov 20 '22 02:11

Rikon


Here's the implementation of what @Rikon said:

public static ValidationResult ValidateGoalDate(DateTime? goalDate) {
like image 2
Rick Liddle Avatar answered Nov 20 '22 04:11

Rick Liddle