Tip: Using DateCompareValidator to validate Age
A customer sent us a question on how to validate that an Age was greater than 18 years. We came up with the following simple example to demonstrate the technique.
Step 1: Add a BasicDatePicker and DateCompareValidator to your page and Set the ControlToValidate property. Example:
[HTML/Design View]
<BDP:BasicDatePicker ID="BasicDatePicker1" runat="server" /> <BDP:DateCompareValidator
ID="AgeCompareValidator"
runat="server"
ControlToValidate="BasicDatePicker1"
ErrorMessage="Must 18 years or older."
Operator="LessThanEqual">
</BDP:DateCompareValidator>
The key to making this all work is setting the DateToCompare property of the DateCompareValidator to a Date 18 years in the past.
Step 2: Add the following to your code behind (Page_load). Example:
[Visual Basic]
Me.AgeCompareValidator.DateToCompare = DateTime.Today.AddYears(-18)
[C#]
this.AgeCompareValidator.DateToCompare = DateTime.Today.AddYears(-18);
To test the above sample, open the WebForm in a browser and type the following:
1. Within the Date Picker TextBox, type "t-18y" (without quotes), then tab off. The Selected Date will be set to "Today minus 18 years", which will pass the DateCompareValidator.
2. Click inside the TextBox and hit the up-arrow on your keyboard which will add one day to the above date. This new date will fail validation.
Related to the above Age Validation, if you want to Calculate an Age based on a supplied Date, the following Age() Method can be used from your code-behind. Example:
[C#]
/// <summary>
/// Calculates the Age based on a given birth date.
/// </summary>
/// <param name="birthDate">Birth date to calculate age.</param>
/// <returns>Returns the age as an Integer.</returns>
public int Age(DateTime dateOfBirth)
{
if (DateTime.Today.Month < dateOfBirth.Month || DateTime.Today.Month == dateOfBirth.Month && DateTime.Today.Day < dateOfBirth.Day)
{
return DateTime.Today.Year - dateOfBirth.Year - 1;
}
else
{
return DateTime.Today.Year - dateOfBirth.Year;
}
}
Hope this helps.
Thanks,
Geoffrey McGill
----------------------------------------
Coolite Inc.
Email: support [at] coolite [dot] com
Phone: +1(888)775-5888