我有一个小问题,这是我的代码:
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/