所需日期时间(+ 18年)

ElH*_*hin 1 asp.net-mvc datetime required

我有一点问题,这是我的代码:

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

我如何限制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");
}
Run Code Online (Sandbox Code Playgroud)

谢谢 ;)

更新:我遵循Berkay Yaylaci的解决方案,但我得到一个NullReferenceException.似乎我的值参数是默认值,然后我的方法没有发布,为什么?解决方案是什么?

Ber*_*kay 5

您可以编写自己的验证.首先,创建一个类.

我打电话给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;

        }
    }
Run Code Online (Sandbox Code Playgroud)

SampleModal.cs

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

IsValid在发布后运行并检查限制.如果年龄不大于限制(我们在模态中给出的!),则返回ValidationResult

希望有帮助,