简体   繁体   中英

How to apply regular expression for Date format MM/DD/YYYY HH:MM:SS am/pm in ASP.NET

I have a TextBox where I am taking input from as user as dd/mm/yyyy hh:mm:ss . Now, I want to validate it with a regular expression. I'm not sure how to apply the expression. I have attached my code as well.

  <tr>
      <td style="width: 30%" class="EcommLabel">
          Date From
      </td>
      <td style="width: 70%" class="EcommLabel">
          <asp:TextBox ID="txtDateFrom" CssClass="EcommNormalTextBox" runat="server">
          </asp:TextBox>MM/DD/YYYY<br />

      <%-- <asp:RegularExpressionValidator ID="regDateFrom" ValidationExpression="^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$" ControlToValidate="txtDateFrom" ValidationGroup="Promotion" runat="server" ErrorMessage="Invalid Date"></asp:RegularExpressionValidator>--%>

      <asp:RangeValidator runat="server" ID="rvDateFrom" Type="Date" ControlToValidate="txtDateFrom" MaximumValue="3000/12/31" MinimumValue="2000/1/1" ErrorMessage="Invalid Date" Display="Dynamic" ValidationGroup="Promotion" />
      </td>
  </tr>

use this expression "(\\d{2}):(\\d{2}):(\\d{4}):(\\d{2}):(\\d{2}):(\\d{2})" like

<asp:RegularExpressionValidator ID="regDateFrom" ValidationExpression="(\d{2}):(\d{2}):(\d{4}):(\d{2}):(\d{2}):(\d{2})"
                                    ControlToValidate="txtDateFrom" ValidationGroup="Promotion" runat="server"
                                    ErrorMessage="Invalid Date"></asp:RegularExpressionValidator>

Also see the following stackoverflow questions:
How to write a regex for MM:DD:YYYY:HH:MM:SS
MM/DD/YYYY HH:MM:SS AM/PM date validation regular expression in javascript

Hope it helps!

Change of your regular expression would do it.

Use the following regular expression

^([1-9]|([012][0-9])|(3[01]))-([0]{0,1}[1-9]|1[012])-\\d\\d\\d\\d [012]{0,1}[0-9]:[0-5][0-9]:[0-5][0-9]$

It will validate the value 01-12-2011 19:59:59

<asp:RegularExpressionValidator ID="regDateFrom" 
  ValidationExpression="^([1-9]|([012][0-9])|(3[01]))-([0]{0,1}[1-9]|1[012])-\d\d\d\d [012]{0,1}[0-9]:[0-5][0-9]:[0-5][0-9]$"  
  ControlToValidate="txtDateFrom" ValidationGroup="Promotion" 
  runat="server"
  ErrorMessage="Invalid Date">
</asp:RegularExpressionValidator>

I have a date picker where I am taking input from as user as MM/DD/YYYY. I want to validate it with a regular expression. Find Below code it might be help full.

expression = "^([0]{0,1}[1-9]|1[012])/([1-9]|([012][0-9])|(3[01]))/[0-9]{4}$";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM