Click here to Skip to main content
15,911,139 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Every one,

I am using c#. i have textbox in which i add calender extender of ajax.
I want to check that enter value in textbox is date or any simple text.

But i don't know what code will be used?

Please help me.

I want to validate that value entered in textbox is date or not?
Posted
Updated 23-May-12 18:57pm
v2

You can try this, if you want to do it at Server Side

DateTime curDate = DateTime.Now;
if (DateTime.TryParse(ToDate, out curDate))
{
\\Your Code goes here
}

Hope this helps.
 
Share this answer
 
Comments
coolnavjot31 24-May-12 1:37am    
Hello Rajesh,

I have also found another solution.

try
{
txtDt.Text = Convert.ToDateTime(txtDt.Text).ToString("dd-MMM-yyyy");
}
catch (Exception eee)
{
txtDt.Text = "";
}
if (txtDt.Text.Trim() == "")
{
ClientScript.RegisterStartupScript(GetType(), ClientID, "alert('Enter Valid Date');", true);
return;
}
Rajesh Kariyavula 24-May-12 1:54am    
I'm happy that you found multiple solutions. But I'm not comfortable with the above code.
Exception is catched and not handled properly. Its a good practice to handle n log the exceptions.

Convert.ToDateTime(txtDt.Text).ToString("dd-MMM-yyyy");
ToString will not handle null, if the txtDt.Text is null, an exception is fired.

And date format is hardcoded, which is not a good practice.

And if (txtDt.Text.Trim() == "") . Please avoid too much code and especially conditional code blocks(if they can be avoided).

Hope you will get it
coolnavjot31 24-May-12 2:10am    
thanks rajesh !
in c#

you can use
Convert.ToDateTime(txtDate.Text)
with in a try - catch statement

if error then you can blank textbox

C#
try
{
    txtDt.Text = Convert.ToDateTime(txtDt.Text).ToString("dd-MMM-yyyy");
}
catch (Exception eee)
{
    txtDt.Text = "";
}
if (txtDt.Text.Trim() == "")
{
    ClientScript.RegisterStartupScript(GetType(), ClientID, "alert('Enter Valid Date');", true);
    return;
}
 
Share this answer
 
Here is what you put in the button:
HTML
<input type="submit" id="btnSubmit" value="Submit" onClick="return Validate();"/>

Javascript
JavaScript
<script type="text/javascript">
<!--

 function Validate()
 {

  var intFlag = 0;
  var strErrMsg = "Please complete the following field(s):\n\n";

  var dtDate= document.getElementById("tbDate").value; // tbDate = name of text box
  var currentDate= getCalendarDate()


  if (dtDate > currentDate )
  {
   strErrMsg = strErrMsg + "your custom error message \n";
   intFlag++;
  }

    // Display error message if a field is not completed
  if (intFlag != 0)
  {
   alert (strErrMsg);
   return false;
  }
  else
   return true;

 }

//-->
</script>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900