2016-07-01 32 views
0

我有一个小问题,这里是我的代码:所需的日期时间(18年)

public partial class Tourist 
    { 

     public Tourist() 
     { 
      Reserve = new HashSet<Reserve>(); 
     } 
     public int touristID { get; set; } 

     [Required] 
     [StringLength(50)] 
     public string touristNAME { get; set; } 

     public DateTime touristBIRTHDAY { get; set; } 

     [Required] 
     [StringLength(50)] 
     public string touristEMAIL { get; set; } 

     public int touristPHONE { get; set; } 

     public virtual ICollection<Reserve> Reserve { get; set; } 
    } 
} 

我怎样才能限制touristBIRTHDAY是18年老?我认为我必须使用这个功能,但我不知道该把它放在哪里: 注意:这个功能就是一个例子。

DateTime bday = DateTime.Parse(dob_main.Text); 
DateTime today = DateTime.Today; 
int age = today.Year - bday.Year; 
if(age < 18) 
{ 
    MessageBox.Show("Invalid Birth Day"); 
} 

感谢;)

更新: 我跟随Berkay Yaylaci的解决方案,但我得到一个NullReferenceException。这似乎是我的价值参数是默认的,然后我的方法不张贴,为什么?有什么解决方案?

回答

4

您可以编写自己的验证。首先,创建一个班级。

我叫MinAge.cs

public class MinAge : ValidationAttribute 
    { 
     private int _Limit; 
     public MinAge(int Limit) { // The constructor which we use in modal. 
      this._Limit = Limit; 
     } 
     protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
     { 
       DateTime bday = DateTime.Parse(value.ToString()); 
       DateTime today = DateTime.Today; 
       int age = today.Year - bday.Year; 
       if (bday > today.AddYears(-age)) 
       { 
        age--; 
       } 
       if (age < _Limit) 
       { 
        var result = new ValidationResult("Sorry you are not old enough"); 
        return result; 
       } 


      return null; 

     } 
    } 

SampleModal.cs

[MinAge(18)] // 18 is the parameter of constructor. 
public DateTime UserBirthDate { get; set; } 

IsValid的岗位后运行并检查极限。如果年龄不超过限制(这是我们在模式给了!)比返回为ValidationResult

希望帮助,

+0

谢谢!我做了你所说的,但有些工作不太好。例如,我创建了一个旅游者1,其中的生日是:10-05-1990,它的工作非常好。然后,我尝试创建一个Tourist 2,其中的生日是12-22-1994,它应该可以正常工作,但是会导致出现“用户代码未处理NullReferenceException”。为什么? 注意:NullReferenceException在“DateTime bday = DateTime.Parse(value.ToString());” – ElHashashin

+0

@ElHashashin上弹出我猜这个格式是错误的。你检查了第一个的格式吗?是10月22日还是12月12日? – Berkay

+0

格式是MM-DD-YYYY,所以它是12月22日 – ElHashashin

1

在您的旅游课堂上实施IValidatableObject。

把你的逻辑放在Validate()方法中。

您正在使用MVC,因此没有MessageBox.Show()。 MVC模型联编程序会自动调用您的验证例程。

下面是与细节How do I use IValidatableObject?

而且你的年龄的逻辑是错误的另一个问题SO。它需要是

DateTime now = DateTime.Today; 
int age = now.Year - bday.Year; 
if (now < bday.AddYears(age)) age--; 
相关问题