tags:

views:

106

answers:

6

I am working in asp.net and I want to take DOB from user in a text box,how can i validate the testbox for feb and leap year consideration.I also want the date to be entered in DD/MM/YYYY.

+1  A: 

Try using regular expression validator in ASP.NET .. Something like this :

<asp:RegularExpressionValidator ID="RegExpVal1" runat="server" ControlToValidate="{Here Goes your Text Box}" ErrorMessage="DOB has to be in dd/mm/yyyy format" ValidationExpression="^([1-9]0[1-9][12][0-9]3[01])[- /.]([1-9]0[1-9]1[012])[- /.][0-9]{4}$" >*</asp:RegularExpressionValidator>

EDIT : I missunderstood your question (tnx to @rob). So maybe you can use Custom validator. Something like this :

<asp:CustomValidator ID="MyValidator" runat="server" 
    ErrorMessage="Invalid date!"
    ControlToValidate="tbDOB" 
    OnServerValidate="MyValidator_ServerValidate">
</asp:CustomValidator>

Add above to your DateTime user control. And now check for valid date:

    public partial class DateTime_EditField : System.Web.DynamicData.FieldTemplateUserControl
    {
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void MyValidator_ServerValidate(object source, ServerValidateEventArgs args)
    {
        DateTime temp;
        String textDate = tbDOB.Text;

        if (DateTime.TryParse(textDate, out temp))
        {
            args.IsValid = true;
        }
        else
        {
            args.IsValid = false;
        }
    }
}
rjovic
-1, Sorry, this doesn't handle `validate the testbox for feb and leap year consideration` as the OP asked.
Rob
@Rob : fair enough...
rjovic
+1  A: 

Try this -

// <summary>
// Determine if Date String is an actual date
// Date format = MM/DD/YYYY
// </summary>
// <param name="date"></param>
// <returns></returns>
private bool ValidateDate(string date)
{
    try
    {
        // for US, alter to suit if splitting on hyphen, comma, etc.
        string[] dateParts = date.Split('/');

        // create new date from the parts; if this does not fail
        // the method will return true and the date is valid
        DateTime testDate = new 
            DateTime(Convert.ToInt32(dateParts[2]), 
            Convert.ToInt32(dateParts[0]), 
            Convert.ToInt32(dateParts[1]));

         return true;
    }
    catch
    {
        // if a test date cannot be created, the
        // method will return false
        return false;
    }
}
Sachin Shanbhag
It seems inelegant to throw an exception when there are existing methods for testing date strings.
RedFilter
+1  A: 

You can use DateTime.TryParseExact:

string dateString = "22/07/1876";
DateTime dateOut;
if ((DateTime.TryParseExact(dateString, "dd/MM/yyyy",
                  new CultureInfo("en-US"),
                  DateTimeStyles.None,
                  out dateOut)))
    Console.WriteLine("Date is valid: {0}", dateOut.ToString());
else
    Console.WriteLine("Date string {0} is invalid.", dateString);
RedFilter
+1  A: 

The best thing to do is use the DateTime.ParseDate method:

var date = "01/10/1981";

var parsedDate = new DateTime();
if (DateTime.TryParse(date, out parsedDate))
{
    // Date is valid and is now in "date"
}
else
{
    // Date is NOT valid / parseable
}
Rob
+2  A: 

These validation code also works .

<asp:CompareValidator ErrorMessage="(mm/dd/yyyy)" Display="Dynamic" ID="valcDate" ControlToValidate="txtDate" Operator="DataTypeCheck" Type="Date" runat="server"></asp:CompareValidator>           

<asp:RangeValidator ID="valrDate" runat="server" ControlToValidate="txtDate" MinimumValue="12/31/1950" MaximumValue="1/1/2100" Type="Date" text="Invalid Date" Display="Dynamic"/>
GayaMani
+1  A: 

I don't understand why all of you try to reinvent the wheel, use regular expression for validating with the format you want the date to be in http://regexlib.com/Search.aspx?k=date&amp;c=-1&amp;m=5&amp;ps=50 has allot of great regex that takes leap years and so on.

Joakim