Share via


Validating date of birth

Question

Sunday, March 3, 2013 10:23 AM

Hello All, 

On my websites registeration form, I am trying to do a client side validation for users birthday.

I want to validate if the birthdate entered by user is between current year and past 100 years.

I am new to this and below is my code, which doesnt work

Validation.Add("DOB_Year",
        Validator.Range(
        
        minValue:DateTime.Today.AddYears(-100),
        maxValue:DateTime.Today.ToString,
        errorMessage: "Invalid Year"
        ));

I know my code is invalid. 

Can anyone please help me on how to do this

Thanks

 

All replies (13)

Tuesday, March 5, 2013 4:34 PM âś…Answered

Ah. You don't have one single field for the date. You are concatenating it from multiple fields. That's why the single field validator I created doesn't work for you. Validators only work for form fields.

Get rid of the following line:

Validation.Add("BirthDay", CustomValidator.Birthday());

then use the body of the validator method like this (the first 3 lines are already in your code - I leave them here so you can see where to place the rest of the code):

DOB_Month=Request.Form["DOB_Month"];
DOB_Day=Request.Form["DOB_Day"];
DOB_Year=Request["DOB_Year"];
DateTime bd;
BirthDay=string.Concat(DOB_Year,"/",DOB_Month,"/",DOB_Day);
if(DateTime.TryParse(Birthday, out bd){
    if(bd > DateTime.Now || bd < DateTime.Now.AddYears(-100)){
        ModelState.AddError("DOB_Year", "Birthday must be before today and less than 100 years ago");
    }
}
else {
    ModelState.AddError("DOB_Year", "Please choose a year, month and day");
}
    

Sunday, March 3, 2013 10:30 AM

You are currently using a DateTime and a string for your minimum and maximum values. Try setting both of them to use DateTime objects :

Validation.Add("DOB_Year",
        Validator.Range(
              minValue:DateTime.Today.AddYears(-100),
              maxValue:DateTime.Today,
              errorMessage: "Invalid Year"
        )
);

Sunday, March 3, 2013 10:34 AM

use rangevalidator. in pageload event set max and min value using DayeTime.Now.ToShortDateString() and DateTime. Now.AddYears(-100).ToShortDateString()


Sunday, March 3, 2013 11:03 AM

@Rion, 

I get below error 

The best overloaded method match for 'System.Web.WebPages.Validator.Range(int, int, string)' has some invalid arguments


Sunday, March 3, 2013 11:05 AM

use rangevalidator. in pageload event set max and min value using DayeTime.Now.ToShortDateString() and DateTime. Now.AddYears(-100).ToShortDateString()

Can you please show me how to do this, I am new to this


Sunday, March 3, 2013 11:08 AM

After looking at the documentation for the Validator.Range() method, it doesn't look like it is built to handle minimum and maximum DateTime values.

You'll likely want to use a RangeValidator similar to what oned_gk suggested : 

<asp:TextBox ID="YourDateTimeText" runat="server" />
<!-- Example Range Validator -->
<asp:RangeValidator ID="RangeValidator1"
                    runat="server"
                    ControlToValidate="YourDateTimeText"
                    ErrorMessage="RangeValidator"
                    MaximumValue=DateTime.Now.Date.ToString("MM/dd/yyyy");
                    MinimumValue=DateTime.Now.Date.AddYears(-100).ToString("MM/dd/yyyy")
                    Type="Date">
</asp:RangeValidator>

Sorry for any typos, I'm not around a development environment currently.


Sunday, March 3, 2013 11:43 AM

Try sumitd answer

        string strYear = "1998";
        string strMonth = "4";
        string strDay = "5";
        DateTime d1 = DateTime.Now;
        DateTime d2 = new DateTime(Convert.ToInt32(strYear), Convert.ToInt32(strMonth), Convert.ToInt32(strDay));
        TimeSpan difference = d1.Subtract(d2);
        if(difference.TotalDays/365.25 > 18)
            Response.Write((difference.TotalDays/365.25).ToString());


Sunday, March 3, 2013 11:43 AM

Sorry, 

I forgot to mention that I am using ASP.Net Razor syntax


Monday, March 4, 2013 2:06 AM

Anybody knows how to do this in Razor syntax


Monday, March 4, 2013 2:33 PM

You can create a custom validator for this

http://www.mikesdotnetting.com/Article/195/ASP.NET-Web-Pages-Creating-Custom-Validators

Put the following into a C# class file named BirthdayValidator.cs and place it in a folder named App_Code (exactly like that) in your root folder:

using System;
using System.Web.WebPages;
using System.Web;

public class BirthdayValidator : RequestFieldValidatorBase
{
    public BirthdayValidator(string errorMessage = null) : base(errorMessage){}

    protected override bool IsValid(HttpContextBase httpContext, string value){
        DateTime bd;
        if(DateTime.TryParse(value, out bd)){
            return bd < DateTime.Now && bd > DateTime.Now.AddYears(-100);
        }
        return false;
    }
}

public class CustomValidator
{
    public static IValidator Birthday(string errorMessage = null){
        if(string.IsNullOrEmpty(errorMessage)){
            errorMessage = "Must be a date between 100 years ago and today";
        }
        return new BirthdayValidator(errorMessage);
    }
}

Then you call it like this in your page:

Validation.Add("Birthdate", CustomValidator.Birthday());

"Birthdate" is assumed to be the "name" of your form field.


Tuesday, March 5, 2013 2:36 AM

@Mike, 

Like always thank you for the answer.

I tried the above code, but no matter what date I put in, it won't validate and gives the validation error.

e.g. I put in a date as 10/20/1983 it wont validate. I have tried several dates between today and 100 yrs ago, but none of them work.


Tuesday, March 5, 2013 8:38 AM

Works fine for me, although your date format doesn't. It needs to be 20/10/1983 with my regional settings. Try entering dates in the following format:

yyyy-mm-dd

If that doesn't work, double check the code you have htere and compare it to what I posted.


Tuesday, March 5, 2013 11:24 AM

If that doesn't work, double check the code you have htere and compare it to what I posted.

Hello Mike, 

The date format I am using is yyyy/mm/dd, I would appreciate if you could please check my HTML code below. I have removed many codes and shorten my html with only the required codes relevant to this thread.

@section Scripts {
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
}

@{
    Layout = "~/_SiteLayout.cshtml";
    Page.Title = "Register";

    // Initialize general page variables
    var email = "";
    var password = "";
    var confirmPassword = "";
    var UserName = "";
    var DOB_Year="";
    var DOB_Month="";
    var DOB_Day="";
    var BirthDay="";
    
    // Setup validation
    Validation.RequireField("email", "You must specify an email address.");
    Validation.Add("email", 
        Validator.Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", 
        "Invalid email address"));

    Validation.RequireField("password", "Password cannot be blank.");
    Validation.RequireField("UserName", "You must specify a UserName.");    
    Validation.RequireField("DOB_Year", "You must specify a Birth Year.");
    Validation.Add("DOB_Year", Validator.Integer("Year must be all numbers"));
    Validation.Add("DOB_Year",
           Validator.StringLength( minLength: 04, maxLength: 04,
           errorMessage: "Year must be 4 numbers"));

    Validation.Add("BirthDay", CustomValidator.Birthday());
    
        
    
    Validation.Add("confirmPassword",
        Validator.EqualsTo("password", "Password and confirmation password do not match."));
    Validation.Add("password",
        Validator.StringLength(
            maxLength: Int32.MaxValue,
            minLength: 6,
            errorMessage: "Password must be at least 6 characters"));
                

    // If this is a POST request, validate and process data
    if (IsPost) {
        AntiForgery.Validate();
        email = Request.Form["email"];
        UserName=Request.Form["UserName"];
        password = Request.Form["password"];
        confirmPassword = Request.Form["confirmPassword"];
        DOB_Month=Request.Form["DOB_Month"];
        DOB_Day=Request.Form["DOB_Day"];
        DOB_Year=Request["DOB_Year"];
        BirthDay=string.Concat(DOB_Year,"/",DOB_Month,"/",DOB_Day);
        



        // If all information is valid, create a new account
        if (Validation.IsValid()) {
            // Insert a new user into the database
            var db = Database.Open("StarterSite");
             db.Execute("INSERT INTO UserProfile (Email, UserName, BirthDay) VALUES (@0, @1, @2,)", email, UserName, BirthDay);
}
}}

<form method="post">
    @AntiForgery.GetHtml()
    @* If at least one validation error exists, notify the user *@
    @Html.ValidationSummary("Account creation was unsuccessful. Please correct the errors and try again.", excludeFieldErrors: true, htmlAttributes: null)

    <fieldset>
        <legend>Fill the information below and get started</legend>
        <ol>
        
            <li class="UserName">
                <label for="UserName" @if(!ModelState.IsValidField("UserName")){<text>class="error-label"</text>}></label>
                <input type="text" id="UserName" name="UserName" placeholder="User Name" value="@UserName" maxlength="25" @Validation.For("UserName") />
                @Html.ValidationMessage("UserName")
            </li>

            <li class="email">
                <label for="email" @if(!ModelState.IsValidField("email")){<text>class="error-label"</text>}></label>
                <input type="text" id="email" name="email" placeholder="Email address" value="@email" @Validation.For("email") Title="email here" />
                @* Write any email validation errors to the page *@
                @Html.ValidationMessage("email")
            </li>
            
<li class="BirthDay">

 @Html.ValidationMessage("BirthDay")
                
<label for="BirthDay">BirthDay</label>
<select name="DOB_Month">
<option value="">Month</option> 
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
<option value="4">Apr</option>
<option value="5">May</option>
<option value="6">Jun</option>
<option value="7">Jul</option>
<option value="8">Aug</option>
<option value="9">Sep</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>

<select name="DOB_Day">
<option value="">Day</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select> 
                    
<input type="text" id="DOB_Year" name="DOB_Year" value="@DOB_Year" maxlength="4" style="width: 40px" placeholder="Year"@Validation.For("DOB_Year") />
                @Html.ValidationMessage("DOB_Year")
            </li>
            <li class="password">
                <label for="password" @if(!ModelState.IsValidField("password")) {<text>class="error-label"</text>}></label>
                <input type="password" id="password" name="password" placeholder="Password" @Validation.For("password") />
                
                @Html.ValidationMessage("password")
            </li>
            <li class="confirm-password">
                <label for="confirmPassword" @if(!ModelState.IsValidField("confirmPassword")) {<text>class="error-label"</text>}></label>
                <input type="password" id="confirmPassword" name="confirmPassword" placeholder="Confirm password" @Validation.For("confirmPassword") />
                
                @Html.ValidationMessage("confirmPassword")
            </li>
</ol>
        
        <input type="submit" value="Register" />
            </fieldset>
</form>