AnswerBun.com

How to calculate age by input field date on the frontend?

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

Stack Overflow Asked by software is fun on February 21, 2021

1 Answers

One Answer

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

Add your own answers!

Related Questions

Implementing an interface with partial delegation

1  Asked on November 22, 2021 by fabrizio

   

postgresql execute dynamic sql command

2  Asked on November 22, 2021 by boothy

 

How to make dict from dataframe?

2  Asked on November 22, 2021 by oumayma-hamdi

       

IOS Full Screen App: why does toolbar appears when page changes?

1  Asked on November 22, 2021 by joel-hoelting

     

azure build pipeline does not start as triggered

2  Asked on November 22, 2021 by oleksa

 

How to fix Exception with queryStringParameters?

1  Asked on November 22, 2021 by mvn-2047

     

PostGIS ST_X() precision behaviour

1  Asked on November 22, 2021 by vance-tunnicliffe

     

merge Map and Array of objects by key

2  Asked on November 22, 2021

   

Changing react barcode format

1  Asked on November 22, 2021 by mig_08

   

MongoDB Document of Size 300kb taking 8-15s

2  Asked on November 22, 2021 by liqteq-developer

   

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved.