0

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).

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
software is fun
  • 7,286
  • 18
  • 71
  • 129

1 Answers1

2

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.

Rufus L
  • 36,127
  • 5
  • 30
  • 43
  • I lost you at the if statement. – software is fun Sep 01 '20 at 13:56
  • It's not enough to subtract the year, so that line checks the actual date. For example if you were born in October but it's only September, then you haven't had a birthday yet so we subtract `1` from the age. – Rufus L Sep 01 '20 at 14:20