asp.net-mvc - 需要日期时间(+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。貌似我的value参数是default,然后我的method就是不post了,为什么呢?有什么解决方案?

最佳答案

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

我调用了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

https://stackoverflow.com/questions/38149190/

相关文章:

python - 找到坡度最陡的点 python

selenium - java.lang.NoClassDefFoundError : freema

laravel - 仅在 Laravel 中公开某些授权路由

android - 完成其他 Activity 之前的所有 Activity

bash - 在 byobu 选项卡中启动命令的脚本

r - 如何在 R 中将一个字符列拆分为多个列

ruby - 符号有什么用?

google-api - Google Classroom API 修改附件

android - JSONObject.put(string,string) 不工作

php - 在 Laravel 迁移中更改列类型的最佳方法是什么?