0

我正在尝试将数据验证添加到我的 DateTime 属性中,我想强制用户选择介于DateTime.Now和小于一年之后的日期DateTime.now.addyears(+1) 这是我的代码:

 public class DateDebut : ValidationAttribute
        {
            public override bool IsValid(object value)
            {
                if (value == null) return false;
                DateTime enteredDate = (DateTime)value;

                if ( (enteredDate >= DateTime.Now) && (enteredDate <= DateTime.Now.AddYears(+1)))
                    return true;
                else
                    return false;
            }
        }
        [Required]
        [Display(Name = "De : ")]
        [DataType(DataType.Date)]
        [DateDebut(ErrorMessage="Date invalide")]
        public DateTime dd { get; set; }

此自定义验证不起作用,验证未执行,我认为我错过了一些非常简单的事情吗?

4

2 回答 2

2

我完全同意丹尼尔,

但是我发现当我需要比较模型中的属性时,我使用 IValidatableObject

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.ivalidatableobject.aspx

我发现对于大多数小类型的比较来说它更快更容易,你会有一些看起来像这样

public class myModel : IvalidatableObject
{
 string debut = DateTime.Now.ToShortDateString();
 string fin = DateTime.Now.AddYears(+1).ToShortDateString(); 
 [Required]
 [Display(Name = "De : ")]
 [DataType(DataType.Date)]
 public DateTime dd { get; set; }

  public IEnumerable<ValidationResult> Validate()
  {
    if(this.debut > this.fin)
    {
      yield return new ValidationResult("debut cannot be greated then fin");
    }
  }
}

阅读并查看最适合您的内容

于 2012-05-24T20:09:40.933 回答
1

属性本质上是静态的。您是否考虑过编写自己的属性进行验证?网络上有几个示例可以帮助您入门。

您还可以根据需要继承RangeAttribute并注入它。

于 2012-05-24T19:41:46.733 回答