CompareValidator for "dd/mm/yyyy" format

BizApps picture BizApps · Jan 16, 2013 · Viewed 11.8k times · Source

I am enhancing our existing web application that will be used on EMEA where I need to change the date format from "mm/dd/yyyy" to "dd/mm/yyyy" at runtime based on the user's global region.

My problem is that my required validation is not accepting the "dd/mm/yyyy" format.

<asp:CompareValidator ID="cvDateReportCompleted" runat="server" ErrorMessage="Report Date is not in correct format" ControlToValidate="txtDateReportCompleted" Operator="DataTypeCheck" Type="Date" ValidationGroup="vgMain" Display="None"></asp:CompareValidator>

Can anyone provide the details to deal with this problem that asp:CompareValidator will accept either "mm/dd/yyyy" or "dd/mm/yyyy"?

Answer

Vishal Suthar picture Vishal Suthar · Jan 16, 2013

You have to consider this before going further:

The CompareValidator is pretty particular about the dates that it will accept. For example, the following dates are not considered valid:

January 1, 2001
Jan 1, 2001

The CompareValidator requires a date that looks like this:

1/1/2001
1-1-2001

http://www.informit.com/articles/article.aspx?p=25461&seqNum=5

Solution:

By default the ASP.Net CompareValidator does not work for dd/mm/yyyy format hence we will need to change the Culture property of the page to en-GB in the @Pagedirective of the ASP.Net Web Page as show below

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" 
Inherits="_Default" Culture = "en-GB" %>

Live demo