Stack Overflow Asked by software is fun on February 21, 2021
I have a model which has a field called
public DateTime birthday {get ; set; } = DateTime.Today;
public int age = 0;
My Razor file
<div class="wrap-input100 validate-input">
<InputDate class="input100" id="birthday" @bind-value="CurrentCustomerModel.birthday" />
</div>
so what I am trying to do is some front end validation. If the person is less than 50 years old, I want to display a message saying "Sorry you are too young" (or anything).
Age
should not be stored data - it's a calculated value based on the time of the query; therefore I would recommend making it a read-only property that's calculated on the fly:
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;
}
}
Now you have a calculated field that will give the accurate Age
(in years), which you can then use to compare against 50
.
Note that the age calculation comes from this answer.
Correct answer by Rufus L on February 21, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP