I am working with an HTML form that accepts 4 dates, two of which are optional. These dates are inserted into the MS SQL database, so I check the boundaries of the DateTime variables that are passed from the form to SqlDateTime.MinValue and SqlDateTime.MaxValue. This is 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")]
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 additional values. In my controller, my ModelState.IsValid returns false, and I get a validation error message:
"Failed to convert the value of type" null "to" System.DateTime ", as expected, using the GoalManager.Models.Goal.ValidateGoalDate method. Must enter a valid date.
Having selected the code, I see that the custom validator does not start in optional fields, but when I remove the DataAnnotation from these optional fields, I do not return an error. If the user does not insert the date in the field, I want to insert NULL into the table. How do I tell Validator that I donβt want the error to check for an empty (or null) date to ignore it and insert zero into the database?
source share