DataAnnotation和可选的DateTime值

jun*_*gos 4 c# asp.net data-annotations asp.net-mvc-3

我正在使用一个接受4个日期的HTML表单,其中两个是可选的.这些日期被插入到MS SQL数据库中,所以我边界检查从表单传递的DateTime变量,对SqlDateTime.MinValueSqlDateTime.MaxValue.这是我的模型的样子:

        [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; }
Run Code Online (Sandbox Code Playgroud)

我的自定义验证器:

    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;
    }
Run Code Online (Sandbox Code Playgroud)

每当您提交没有可选值的表单时,就会出现问题.在我的控制器中,我的ModelState.IsValid返回false,我收到验证错误消息:

无法通过方法GoalManager.Models.Goal.ValidateGoalDate将"null"类型的值转换为"System.DateTime".必须输入有效日期.

通过代码,我看到自定义验证器不在可选字段上运行,但是当我从这些可选字段中删除DataAnnotation时,我没有返回任何错误.如果用户没有在字段中插入日期,我想在表中插入NULL.如何告诉Validator我不想错误检查空白(或空)日期,忽略它,并将空值插入数据库?

Rik*_*kon 5

您的自定义验证程序作为参数使用的DateTime在您的示例中不可为空...如果您使其成为可以为空的DateTime,它应该可以解决您的问题.

  • 我不知道.这是一个继承的项目,我一直处于震惊的状态.您应该看到一些其他代码. (3认同)