[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

How to create a Date Range validator in ASP.NET

Posted on 2009-04-19
9
Medium Priority
?
862 Views
Last Modified: 2012-05-06
Hi,
Newbie in the house. I'm creating a simple webpage where a textbox is used for collecting the Date of Birth information. And what i wanted to happen is that information placed on the text box needs to be validated by the following....
1.0     Format (needs to be in dd/mm/yyy)
2.0     Range  (must not be older than 3yrs old and younger than 65 years old compared to current date)
0
Comment
Question by:jsuanque
  • 4
  • 3
  • 2
9 Comments
 
LVL 12

Expert Comment

by:wht1986
ID: 24181649
Here's how i would do it. Add a client side data type check to make sure its a date. Then use a custom validator because you have add odd range like younger than 3 or older than 65 is ok.  Take a look at the code to see if it helps.  the postback is fired on a button press.


    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:CompareValidator ID="EnsureDateValidator" runat="server" 
        ControlToValidate="TextBox1" Display="Dynamic" 
        ErrorMessage="The value must be a date." Operator="DataTypeCheck" Type="Date"></asp:CompareValidator>
    <asp:CustomValidator ID="CheckAgeValidator" runat="server" 
        ControlToValidate="TextBox1" 
        ErrorMessage="Age must be younger than 3 or older than 65." 
        onservervalidate="CheckAgeValidator_ServerValidate"></asp:CustomValidator>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
 
 
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid)
            return;
    }
 
    protected void CheckAgeValidator_ServerValidate(object source, ServerValidateEventArgs args)
    {
        DateTime enteredAge = DateTime.Parse(this.TextBox1.Text);
        
        // is the person under 3
        if (DateTime.Now.Date.AddYears(-3) < enteredAge)
        {
            args.IsValid = true;
            return;
        }
 
        // maybe they are older than 65
        if (DateTime.Now.Date.AddYears(-65) > enteredAge)
        {
            args.IsValid = true;
            return;
        }
 
        // nope
        args.IsValid = false;
    }

Open in new window

0
 

Author Comment

by:jsuanque
ID: 24181720
Sorry i meant older than 3years old and younger than 65 years old (BETWEEN 3 AND 65 is valid)
0
 

Author Comment

by:jsuanque
ID: 24181770
Hi wht1986,

Is the code you attached in VB? cause i';m getting heaps of error message.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 14

Accepted Solution

by:
GiftsonDJohn earned 600 total points
ID: 24182023
Hi

It is not in VB. it is in C#.

You can use like this.

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:RegularExpressionValidator ID="EnsureDateValidator" runat="server"
        ControlToValidate="TextBox1" Display="Dynamic" 
        ErrorMessage="The value must be a date in format(dd/mmm/yyyy)." ValidationExpression="(^((((0[1-9])|([1-2][0-9])|(3[0-1]))|([1-9]))\x2F(((0[1-9])|(1[0-2]))|([1-9]))\x2F(([0-9]{2})|(((19)|([2]([0]{1})))([0-9]{2}))))$)"></asp:RegularExpressionValidator>
    <asp:CustomValidator ID="CheckAgeValidator" runat="server" 
        ControlToValidate="TextBox1" 
        ErrorMessage="Age must be younger than 3 or older than 65." 
        onservervalidate="CheckAgeValidator_ServerValidate"></asp:CustomValidator>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
 
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
    If Not Page.IsValid Then
        Exit Sub
    End If
End Sub
 
Protected Sub CheckAgeValidator_ServerValidate(ByVal source As Object, ByVal args As ServerValidateEventArgs)
    Dim dtf As New DateTimeFormatInfo()
    dtf.ShortDatePattern = "dd/MM/yyyy"
    
    Dim dtDOB As DateTime = DateTime.Parse(Me.TextBox1.Text, dtf)
    Dim age As Integer = DateTime.Now.Year - dtDOB.Year
    
    ' is the person under 3
    If age >= 3 AndAlso age <= 65 Then
        args.IsValid = True
    Else
        args.IsValid = False
    End If
End Sub

Open in new window

0
 
LVL 12

Expert Comment

by:wht1986
ID: 24183934
thanks for posting the VB.NET version Gifts
0
 
LVL 14

Expert Comment

by:GiftsonDJohn
ID: 24186604
It is not just VB.NET another approach and correct age validation.
0
 

Author Comment

by:jsuanque
ID: 24189769
Hi GiftsonDJohn,

Actually it's the simplest code i've ever seen so far..Anyway, this form of mine is a multi-view form and the save or validate button is on the last page.. Upon applying your code...the date format validation works but the age validation seems to be not working.  Note that the DOB text box is in 1st tab while the button is in the second. Do you think this matter?
0
 
LVL 12

Assisted Solution

by:wht1986
wht1986 earned 400 total points
ID: 24190280
If the textbox and the validators are all on the same View of the MultiView then I dont think it should matter.
0
 

Author Closing Comment

by:jsuanque
ID: 31572068
Thanks guys...got it working
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I recently went through the process of creating a Calendar Control of events with the basis of using a database to keep track of the dates that are selectable, one requirement was to have the selected date pop-up in a simple lightbox.  At first this…
ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
Look below the covers at a subform control , and the form that is inside it. Explore properties and see how easy it is to aggregate, get statistics, and synchronize results for your data. A Microsoft Access subform is used to show relevant calcul…
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…
Suggested Courses

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question