简体   繁体   中英

How to validate date format in textbox using ASP.NET c#?

This is my code

WebForm1.aspx:-

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="datetime.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <link type="text/css" href="Content/jquery-ui-1.7.1.custom.css" rel="stylesheet" /> <script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"></script> <script src="Scripts/jquery-ui-1.7.1.custom.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#txtDate").datepicker(); }); </script> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="txtDate" runat="server"></asp:TextBox> &nbsp;&nbsp;&nbsp; <%--<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtDate" ErrorMessage="enter valid date" SetFocusOnError="False" ValidationExpression="^([0]?[0-9]|[12][0-9]|[3][01])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$"></asp:RegularExpressionValidator>--%> <br /> <br /> <br /> </div> </form> </body> </html> 

In the above code i have a textbox , when user click on textbox it opens calender for date selection. When user not select data from calender , user write date manually on textfield how to validate if user enter wrong format. I tried write regularexpression when i use regularexpression calender not showing but validation worked.

If you using the JQuery UI datepicker, I would suggest use JQuery Validation rather than the c# validation. the below should work

$("#txtDate").datepicker();

$("#txtDate").blur(function(){
        val = $(this).val();
        val1 = Date.parse(val);
        if (isNaN(val1)==true && val!==''){
           alert("error")
        }
        else{
           console.log(val1);
        }
});

Add a HTML

tag or something next to text box and if validation fails set the message to your error message. like <p id="myp"> </p> and then edit the above like

if (isNaN(val1)==true && val!==''){
               $("p#myp").text('Date is not valid');
            }

The answer is just a pointer in the right direction, you can use this technique to customise your solution.

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