2

I am using the following code to make sure my textbox has a valid date entered into it:

<asp:CompareValidator ID="cvStartDate" runat="server" Operator="DataTypeCheck" 
Type="Date" ControlToValidate="txtStartDate" ErrorMessage="Please enter the 
start date in the format of dd/MM/yyyy hh:mm"/>

But when I enter a date with a time validation fails. Is there a way to get this type of validator to accept dates with times too or do I have to build a custom validator for this? If I have to go down the custom validation route what would you suggest?

Pete
  • 57,112
  • 28
  • 117
  • 166
  • What is the value you are entering ? do you get any exceptions ? – V4Vendetta Jan 30 '13 at 12:45
  • I entered `30/01/2013 10:00`, no exception but it just showed the error message saying it wasn't a valid date. If I took the 10:00 off it validated ok – Pete Jan 30 '13 at 12:49
  • 2
    `CompareValidator` does not have a `DateTime` type. You'll have to use a `CustomValidator` or a `RegularExpressionValidator`. – juharr Jan 30 '13 at 12:57
  • After much googling I have come to the same conclusion, but I think I have a work around with the use of the date comparer and a couple of dropdownlists for hour and time – Pete Jan 30 '13 at 13:00
  • Is entering both date and time a valid case? – shree.pat18 Nov 06 '13 at 10:05
  • @shree.pat18 I don't understand your question – Pete Nov 06 '13 at 10:24
  • @Pete - Your first line says "...to make sure my textbox has a valid date entered into it" and you say later that "when I enter a date with a time validation fails". I was unable to understand if the case where user enters a date and time is a valid scenario for your application. – shree.pat18 Nov 06 '13 at 10:26
  • ah yes - they needed to enter a valid date that also had a time too - with the following format: `dd/MM/yyyy hh:mm` – Pete Nov 06 '13 at 10:27

2 Answers2

2

@Prabu is correct though. Use CustomValidator.

CompareValidator only works with dates and not date & time.

protected void CustomValidator_Date(object source, ServerValidateEventArgs args)
    {
        IFormatProvider culture = new CultureInfo("en-AU", true);
        try
        {
            String[] formats = { "dd MM yyyy", "dd/MM/yyyy", "dd-MM-yyyy" };
            DateTime dt1;
            dt1 = DateTime.ParseExact(args.Value, formats, culture, DateTimeStyles.AdjustToUniversal);
            args.IsValid = true;
        }
        catch
        {
            args.IsValid = false;
        }
    }
Fandango68
  • 4,461
  • 4
  • 39
  • 74
-1

Its better to use custom validator to validate dates.. To avoid user to enter date and time,

use Ajax calender extender and set readonly property true.

Prabu
  • 21
  • 6