问题描述
public DateTime birthday {get ; set; } = DateTime.Today;
public int age = 0;
我的剃刀文件
<div class="wrap-input100 validate-input">
<InputDate class="input100" id="birthday" @bind-value="CurrentCustomerModel.birthday" />
</div>
所以我想做的是一些前端验证。如果该人不到50岁,我想显示一条消息,“对不起,您太小”(或其他任何东西)。
解决方法
Age
不应存储数据-它是根据查询时间计算得出的值;因此,我建议将其设置为动态计算的只读属性:
public DateTime Birthday { get; set; } = DateTime.Today;
public int Age
{
get
{
var today = DateTime.Today;
var age = today.Year - Birthday.Year;
if (Birthday.Date > today.AddYears(-age)) age--;
return age;
}
}
现在您有了一个计算得出的字段,该字段将给出准确的Age
(以年为单位),然后可以将其与50
进行比较。
请注意,年龄计算来自this answer。