Pete
Pete

Reputation: 58422

CompareValidator date with time

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?

Upvotes: 2

Views: 1383

Answers (2)

Fandango68
Fandango68

Reputation: 4838

@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;
        }
    }

Upvotes: 2

Prabu
Prabu

Reputation: 11

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.

Upvotes: -1

Related Questions