2014-10-26 63 views
2

即使在删除所需的属性后,为什么我得到“出生日期是必需的”错误消息?是否因为任何其他属性?我该如何改变它?我只是检查一下,如果有人提出了不寻常的年龄,我可以找到它。MVC中的数据注释5

namespace ProjectCrux.Models 
{ 
    public class Student 
    { 
     public int studentId { get; set; } 


     [Display(Name = "Date of Birth")] 
     [DataType(DataType.Date)] 
     [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] 
     [DateOfBirth(MinAge = 15, MaxAge = 90, ErrorMessage = "Too young or too old???")] 
     public DateTime dateOfBirth { get; set; } 


     public string salt { get; set; } 
    } 


    /* 
    * Attribute to validate date of birth within a range 
    */ 
    public class DateOfBirthAttribute : ValidationAttribute 
    { 
     public int MinAge { get; set; } 
     public int MaxAge { get; set; } 

     public override bool IsValid(object value) 
     { 
      if (value == null) 
       return true; 

      var val = (DateTime)value; 

      if (val.AddYears(MinAge) > DateTime.Now) 
       return false; 

      return (val.AddYears(MaxAge) > DateTime.Now); 
     } 
    } 
} 

回答

2

您可以使其为空。

public DateTime? dateOfBirth { get; set; }