Geeks With Blogs
Bunch's Blog One day I'll have a catchy subtitle, one day

Probably everyone has at one time or another had a form that needed some sort of date to be entered. If you are like me and use ASP.Net and want to use the ASP calendar control the asp validators don’t work. Well without some work arounds to the calendar control. However if you just needed to validate if the user clicked on a date in the calendar control you can just use the regular calendar control and a customvalidator like this.

The calendar control:

<asp:Calendar ID="caltest" runat="server" Font-Size="Small"></asp:Calendar>

The customvalidator control:

<asp:CustomValidator ID="cvCaltest" runat="server" ErrorMessage="* A date is required" 
ValidationGroup="vgCaltest" ></asp:CustomValidator>

Then I have a button to save the form back to the database. To check the date I would use the following in the button’s click event:

VB.Net

Protected Sub btnCaltest_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCaltest.Click
        Dim x As Date
        x = caltest.SelectedDate
        If x = "12:00:00 AM" Then
            cvCaltest.IsValid = False
            Exit Sub 
        End If
End Sub

C#

protected void btnCaltest_Click(object sender, EventArgs e)
    {
        DateTime x;
        DateTime y = new DateTime();
        x = Calendar1.SelectedDate;
        if (x == y)
        {
            cvCaltest.IsValid = false;
            return;
        }
    }

The cvCaltest.IsValid = False would display the validator’s error message. Right after that I have an Exit Sub so the rest of the code associated with the button click would not run since the validation for the calendar failed. That’s it, nothing fancy but in some cases it is all I need.

Technorati Tags: ,,
Posted on Tuesday, February 17, 2009 3:00 PM ASP.Net | Back to top


Comments on this post: Quick and Dirty Calendar Validation (Date Required)

# re: Quick and Dirty Calendar Validation (Date Required)
Requesting Gravatar...
That was Quick~~~
Left by Roger on Jun 07, 2009 5:16 PM

# re: Quick and Dirty Calendar Validation (Date Required)
Requesting Gravatar...
thanks!!! dirty but works! ;)
Left by mk on May 01, 2010 5:53 AM

# re: Quick and Dirty Calendar Validation (Date Required)
Requesting Gravatar...
it works, thanls a lot
Left by Alex on May 26, 2010 6:34 AM

# re: Quick and Dirty Calendar Validation (Date Required)
Requesting Gravatar...
Dirty but working...
Left by Prince on Nov 29, 2012 2:36 AM

Your comment:
 (will show your gravatar)


Copyright © Bunch | Powered by: GeeksWithBlogs.net