473,810 Members | 3,135 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

validating dates from string input

In C# what is the best way to validate that a particular string
entered by a user will actually convert to a date w/o using a try
catch block or writing code to explicitly parse the string?

Here is what I know I can use, but there are potentially thousands of
dates to validate, and I know this code is inefficient if there are
lots of dates that won't convert...

private DateTime ValidateDate(st ring date)
{
DateTime convertedDate = DateTime.MinVal ue;
try
{
convertedDate = DateTime.Parse( date);
}
catch
{
// throw exception for invalid date
}
return convertedDate;
}

Thanks,
John
Nov 16 '05 #1
4 2581
John,

You can use the code you have, or, if you have access to the .NET 2.0
beta, you can use the static TryParse or TryParseExact method on the
DateTime structure.

Another option would be to call the static IsDate method on the
Interaction class in the Microsoft.Visua lBasic namespace. It is a little
more lenient than the TryParse and the TryParseExact methods.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"John Livermore" <jo************ @nospm-inginix.com> wrote in message
news:7u******** *************** *********@4ax.c om...
In C# what is the best way to validate that a particular string
entered by a user will actually convert to a date w/o using a try
catch block or writing code to explicitly parse the string?

Here is what I know I can use, but there are potentially thousands of
dates to validate, and I know this code is inefficient if there are
lots of dates that won't convert...

private DateTime ValidateDate(st ring date)
{
DateTime convertedDate = DateTime.MinVal ue;
try
{
convertedDate = DateTime.Parse( date);
}
catch
{
// throw exception for invalid date
}
return convertedDate;
}

Thanks,
John

Nov 16 '05 #2
John Livermore wrote:

In C# what is the best way to validate that a particular string
entered by a user will actually convert to a date w/o using a try
catch block or writing code to explicitly parse the string?
Is there a particular reason that you can't use try/catch?
Here is what I know I can use, but there are potentially thousands of
dates to validate, and I know this code is inefficient if there are
lots of dates that won't convert...
How do you know it is inefficient?

Do you have specific performance requirements that aren't being met? If not,
don't worry about the performance.

The first rule of optimization is: don't do it.


private DateTime ValidateDate(st ring date)
{
DateTime convertedDate = DateTime.MinVal ue;
try
{
convertedDate = DateTime.Parse( date);
}
catch
{
// throw exception for invalid date
}
return convertedDate;
}

Nov 16 '05 #3
I have read in many places that try...catch is a means of detecting
errors but it shouldn't be used if you know the error might occur.
Rather you should use other means to detect the condition.
Try...catch is for errors you don't know are going to occur (bugs) to
keep your application behaving nicely.

Your point of don't fix it unless it is broken is well taken, but I
feel this will be an issue for us and should be addressed through some
other means.

We are exploring the use of regular expressions to validate the input
before we attempt to cast it as a date.

On Tue, 07 Sep 2004 12:53:57 -0700, Julie <ju***@nospam.c om> wrote:
John Livermore wrote:

In C# what is the best way to validate that a particular string
entered by a user will actually convert to a date w/o using a try
catch block or writing code to explicitly parse the string?


Is there a particular reason that you can't use try/catch?
Here is what I know I can use, but there are potentially thousands of
dates to validate, and

I know this code is inefficient if there are
lots of dates that won't convert...


How do you know it is inefficient?

Do you have specific performance requirements that aren't being met? If not,
don't worry about the performance.

The first rule of optimization is: don't do it.


private DateTime ValidateDate(st ring date)
{
DateTime convertedDate = DateTime.MinVal ue;
try
{
convertedDate = DateTime.Parse( date);
}
catch
{
// throw exception for invalid date
}
return convertedDate;
}


Nov 16 '05 #4
John Livermore wrote:

I have read in many places that try...catch is a means of detecting
errors but it shouldn't be used if you know the error might occur.
Rather you should use other means to detect the condition.
Try...catch is for errors you don't know are going to occur (bugs) to
keep your application behaving nicely.
You are right, try/catch is for exceptional circumstances -- in theory. If the
framework provided the necessary methods (such as IsDate()), then try/catch
wouldn't be necessary in this case. Since it doesn't, using try/catch is
perfectly acceptable.
Your point of don't fix it unless it is broken is well taken, but I
feel this will be an issue for us and should be addressed through some
other means.

We are exploring the use of regular expressions to validate the input
before we attempt to cast it as a date.
I was going to suggest regex as well, but didn't. You will probably end up w/
a horrendous piece of code that is difficult to maintain, hard to understand,
and susceptible to a multitude of errors. As I'm sure you are well aware,
date/time formats are locale-dependent.

Further, I wouldn't be surprised in the least if the regex version of what you
come up with is quite a bit slower than the try/catch version. I'd be
interested to hear what you find after you write the regex version and compare
it to the try/catch version...

Good luck.

On Tue, 07 Sep 2004 12:53:57 -0700, Julie <ju***@nospam.c om> wrote:
John Livermore wrote:

In C# what is the best way to validate that a particular string
entered by a user will actually convert to a date w/o using a try
catch block or writing code to explicitly parse the string?


Is there a particular reason that you can't use try/catch?
Here is what I know I can use, but there are potentially thousands of
dates to validate, and

I know this code is inefficient if there are
lots of dates that won't convert...


How do you know it is inefficient?

Do you have specific performance requirements that aren't being met? If not,
don't worry about the performance.

The first rule of optimization is: don't do it.


private DateTime ValidateDate(st ring date)
{
DateTime convertedDate = DateTime.MinVal ue;
try
{
convertedDate = DateTime.Parse( date);
}
catch
{
// throw exception for invalid date
}
return convertedDate;
}

Nov 16 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2896
by: The Plankmeister | last post by:
Hi... What's the best method of validating input characters? I would like to prevent users submitting exotic characters (such as those acquired on Windows Systems by pressing ALT+) and thought a way of doing this would be to compare the submitted strings with the array keys returned by get_html_translation_table(HTML_ENTITIES), but padding this array out with all the remaining normal keyboard characters. But... am I reinventing the...
3
2337
by: Terje | last post by:
Hello I have a function like this function checkquantitiy(quantitiy){ if(quantitiy.value != parseInt(quantitiy.value)) { alert(quantitiy.value+" sorry not integer quantitiy"); } } //End of function
8
2243
by: netsurfer | last post by:
Hi: Have a question on making the date automatically filled in by what the user enters in by the date at the top. The date entered at the top would most likely be on a Wednesday then I need to have all the prior dates pop in. Example: User enters 2/9/05 in the date field at the top being a Wednesday...I need the dates at the bottom to be filled in automatically, respectively as 2/3/05, 2/4/05, 2/5/05, 2/6/05, 2/7/05, 2/8/05, 2/9/05...
5
5989
by: Steve | last post by:
I am currently trying to validate data in an access database. I need to verify that columns containing date information are in the format ddmmyyyy and columns containg time information are in the format HH:MM 24. The dates and times are stored in text fields. ie date 12121998, time 20:34 Could anyone suggest a method for validating the fields. What is the syntax for converting text fields into dates and times? Any suggestions...
1
2908
by: panche | last post by:
I'm developing a fairly simple user control that has two textboxes for date/time entry (a from date/time and a to date/time). One of my requirements is that there should be no button that sets these values (i.e., no button to cause a postback). The problem I'm having is that I need a number of validations to be performed on the data entry, but I don't know how to do this without having the user control/page posted back to the server. ...
9
5850
by: chuck | last post by:
I need some help with validating user input. I am writing a C computer program for an intro to C course. Here is the situation. I am creating an application that will do currency conversions. The user will be presented with a list of 5 selections they can make. They will then be prompted for which selection they want to enter (which can only be 1-5, no characters or anything like it). Once they select the number, 1 for Euro, 2 for...
2
1494
by: MadMike42 | last post by:
This is really starting to annoy me, I've got a form, that has some input boxes, a example of the code is here:- <form action="admin_save_stock.asp" method="post" name="MyFormData"> <input name="Make" type="text" id="MenuText" value=<% response.write rsTable("Make") %size="50" maxlength="50"> <input name="DateBought" id="MenuText" type="text" value=<% response.write rsTable("DateBought") % size="10" maxlength="10"> </form>
2
1616
by: Just Me | last post by:
Hi people. I am attempting to determine how best to prevent a users date entry in an update action from causing a format exception. The dates are UK, but the user may try to put in a 'US' format. I have a datasource which is wired to my DAL/update function. 1.) On the server side.
6
4510
by: Richard | last post by:
I'm validating a date and time string which must be EXACTLY of the format yy-mm-dd hh:mm:ss and extracting the six numeric values using sscanf. I'm using the format string "%2u-%2u-%2u %2u:%2u:%2u" which works, but it allows each numeric field to be either 1 or 2 digits in length. Also the man page for sscanf says that preceeding white space before a numeric is ignored.
0
9722
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9603
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10379
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10393
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10124
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7664
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6882
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5690
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.