Validate the Date In Textbox

11,556

Solution 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

Solution 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

Solution 3

DateTime dt;

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


  //do stuff;
}
Share:
11,556
portgas d ace
Author by

portgas d ace

Updated on July 25, 2022

Comments

  • portgas d ace
    portgas d ace almost 2 years

    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>
    
  • portgas d ace
    portgas d ace over 11 years
    I am using a textbox that has a calendarExtender and maskedEditExtender but what if the user type a date and not to choose a date in GUI that is appearing if I click the textbox..
  • Tim Schmelter
    Tim Schmelter over 11 years
    -1 This won't compile since TryParseExact returns a bool which indicates whether it could be parsed to DateTime or not. It also requires to pass a DateTime variable as out parameter.