Validate the Date In Textbox

2019-07-15 22:49发布

问题:

How can I determine if the value in my textbox is a correct date?

ex: this is the value of the date in my Textbox:01/32/2013

I know that it is a wrong value of date, but how can I determine that it is a wrong format? I can avoid that by using try and catch, but I don't want to use it, I will use it if I don't find a solution in my problem.

<asp:TextBox ID="txtMEditStartDt" runat="server" Text='<%# Bind("StartDt", "{0:MM/dd/yyyy}") %>'
    CssClass="datePicker" SkinID="textSkin" Width="100px"></asp:TextBox>
<asp:MaskedEditExtender ID="MaskedEditStartDt" runat="server"
    TargetControlID="txtMEditStartDt" Mask="99/99/9999" MaskType="Date" 
    CultureAMPMPlaceholder="" CultureCurrencySymbolPlaceholder="" 
    CultureDateFormat="" CultureDatePlaceholder="" CultureDecimalPlaceholder="" 
    CultureThousandsPlaceholder="" CultureTimePlaceholder="" Enabled="True"/>
<asp:CalendarExtender ID="calendarEditStartDt" runat="server" TargetControlID="txtMEditStartDt" Format="MM/dd/yyyy">
</asp:CalendarExtender>

回答1:

You can use DateTime.TryParse method. In this method used is a current culture of applicaiton. So in case of failure, it will return simply false.

DateTime dateValue = default(DateTime);
if (DateTime.TryParse(dateString, out dateValue)) 
   //SUCCESS 
else 
  //FAILURE


回答2:

Why dont you make use of Calander control which put data in your Textbox rather than allowing user to enter date.. this will make sure that user not going to enter wrong data value because user need to select date from calander control only

or

if you know the data format than you can do like this

string dateTimeString = "28/08/2012";
DateTime date;
if(DateTime.TryParseExact(dateTimeString, 
   "dd/MM/yyyy", CultureInfo.InvariantCulture,DateTimeStyles.None, 
    out date))
 {
    //code to process valid date
 }

if not valid date than returns false value for it , like this you can validate your data of date



回答3:

DateTime dt;

if(DateTime.TryParse("01/32/2013",out dt)){


  //do stuff;
}