John
John

Reputation: 217

Using validation to check a persons age from todays date

I'm trying to create a to check if a person is between 18 and 25 as of today's date and time. I know I could use a range validator with a date type then manually type in the dates but if someone used the form in the future the dates I typed in would be incorrect. Is there a piece of code I could use to make sure I wouldn't have to keep going back to update the validator every year?

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        rngValDateOfBirth.MinimumValue = DateTime.Now.AddYears(-25).ToString();
        rngValDateOfBirth.MaximumValue = DateTime.Now.AddYears(-18).ToString();
    }

 Date Of Birth <asp:TextBox ID="txtCdob" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="rfvCdob" runat="server" ErrorMessage="You must enter a date of  birth" Text="*" ControlToValidate="txtCDOB" Display="Dynamic">*</asp:RequiredFieldValidator>
        <asp:RangeValidator ID="rngValDateOfBirth" runat="server" ErrorMessage="must be between 18 and 25" ControlToValidate="txtCdob" Type="Date"></asp:RangeValidator>

Upvotes: 1

Views: 1933

Answers (3)

Jonesopolis
Jonesopolis

Reputation: 25370

int age = DateTime.Now.Year - userBirthYear;
if(age > 18 && age < 25)
{

}

DateTime.Now will get the correct time when it is called

Upvotes: 0

JohnLBevan
JohnLBevan

Reputation: 24430

Use DateTime.Now to get the current date & time (or DateTime.UtcNow to avoid timezone concerns). Having this you can calculate someone's age dynamically from their DOB, so no need to update any code on a regular basis.

http://msdn.microsoft.com/en-us/library/system.datetime.aspx

Upvotes: 0

Brandon
Brandon

Reputation: 69983

You cam set the Minimum/Maximum properties in the codebehind.

Untested, but something like this might work:

MyDateRangeValidator.MinimumValue = DateTime.Now.AddYears(-25).ToString(/* format */);
MyDateRangeValidator.MaximumValue = DateTime.Now.AddYears(-18).ToString(/* format */);

Upvotes: 4

Related Questions