Validate date field in asp.net using validator control

Narendra picture Narendra · Aug 1, 2012 · Viewed 8.3k times · Source

I have the following validator control in my page.

<asp:CompareValidator ID="cvPatientDateOfBirth" runat="server"
        ControlToValidate="txtPatientDateOfBirth"  
        ErrorMessage="Enter proper date.(DD/MM/YYYY)" 
        Font-Bold="True" Operator="GreaterThan"  Display="Dynamic"
        ValidationGroup="FirstPreview" CssClass="validatorMsg" 
        SetFocusOnError="True" ValueToCompare="1/1/1100" Type="Date" >
    </asp:CompareValidator>
  • When I type 12/09/1900 it is validating properly. [Good]
  • When I type 12/09/1009 it is not validating properly. [Good]
  • When I type 12/09/09 it is validating. [Not intended]. In this case I want it to validate only if year of date in 4 digits. Otherwise show error message.

If I use both compare validator for date type check and regular expression validator for years(4digit) check, then "12/02/198" is showing error message for both the validators.

Can anyone please tell me how to do that?

Thanks.

Answer

Aghilas Yakoub picture Aghilas Yakoub · Aug 1, 2012

You can use RegularExpressionValidator and set ValidationExpression

ValidationExpression = "\d{1,2}\/\d{1,2}/\d{4}"