473,699 Members | 2,773 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Best (and easiest) way to test that a "date string" (mm/dd/yyyy) is valid

Just looking for the simplest. right now my perl script returns an
error messge to the user if the date string is invalid. would like to
do this before accessing the server.

TX

Dec 3 '06 #1
17 5274
VK

Petyr David wrote:
Just looking for the simplest. right now my perl script returns an
error messge to the user if the date string is invalid. would like to
do this before accessing the server.
How do you get the date string from the user? Does she has to type it
in manually in strict mm/dd/yyyy format in a form's text field?

Dec 3 '06 #2
Petyr David wrote:
Just looking for the simplest. right now my perl script returns an
error messge to the user if the date string is invalid. would like to
do this before accessing the server.
If your date format is not flexible and you don't care to support ancient
browsers, a simple regular expression can quickly test that the input is
well-formed, but can't verify that the values are valid. For that you need
to split the values out and apply some logic.

If you want a solution that does all the work for you and can validate
arbitrary formats, check out my date lib at:
http://www.javascripttoolbox.com/lib/date

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Dec 3 '06 #3
In comp.lang.javas cript message
<11************ **********@l12g 2000cwl.googleg roups.com>, Sun, 3 Dec 2006
10:22:15, Petyr David <ph*****@gmail. comwrote:
>Just looking for the simplest. right now my perl script returns an
error messge to the user if the date string is invalid. would like to
do this before accessing the server.
Always include the question within the article; the Subject is not
necessarily simultaneously visible.

It's a good idea to read the newsgroup and its FAQ. See below. You
could have discovered how to validate standard numeric date strings by
doing that, and then you should be able to adapt it for FFF strings.
Except that your "Best (and easiest) way" is rather meaningless. All
sensible methods are easy, if you only have to copy them. But does
"Best" refer to code size, code speed, or code comprehensibili ty, pr
proving code validity?
And you need to define what is valid. For today, 2006-12-3 is
unambiguous, but it is not valid by ISO 8601, which calls for
2006-12-03. You have only indicated that, for you, mm/dd/yyyy can be
good.

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v6.05 IE 6
<URL:http://www.jibbering.c om/faq/ Old RC FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Dec 3 '06 #4
Petyr David wrote:
Just looking for the simplest. right now my perl script returns an
error messge to the user if the date string is invalid. would like to
do this before accessing the server.
You need to define "valid" and "simplest". The simplest test I can
think of is for 3 numbers separated by "/":

function isValidDate(dat eString){
return /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateStrin g);
}

But that may not be of much use - the input may not be a valid date,
e.g. 2/29/2006 will return true (as will a very large number of other
"valid" input strings).

If you want to check that the date is valid according to your required
mm/dd/yyyy, the easiest way is to firstly check the format, then that
it will generate a valid date:

function isValidDate(dat eString){
if (/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateStrin g)){
var testDate = new Date(dateString );
var dateBits = dateString.spli t('/');
if ( dateBits[1] == testDate.getDat e() &&
(dateBits[0]-1) == testDate.getMon th() ){
return true;
}
}
return false;
}

There are other methods that don't use a date object and may be
considered 'simpler' by some. Expecting mm/dd/yyyy to correctly
generate a date object when used with new Date() may be overly
dependent on browser implementations (the ECMAScript Language
specification doesn't say that it must, but browsers seem to).

Your required format is native to a small percentage of internet users.
You may wish to consider an international format (i.e. one that is not
peculiar to a small number of countries) such as the ISO format:
yyyy/mm/dd.

However, if your criteria for "simple" include implementation, you
might like to use a library such as that suggested by Matt K.

There is a lot of information on dates here:

<URL: http://www.merlyn.demon.co.uk/js-dates.htm >

You might also wish to search the archives, this question is asked
frequently.

<FAQENTRY>
Should there be an FAQ on date validation? It seems to be asked about
very frequently, a search on "validate date" returns 413 records.

There is a suggestion here from JRS that seems a reasonable start:

<URL:
http://groups.google.com.au/group/co...bd380cdf3407f9
>

--
Rob

Dec 4 '06 #5
User types it in form's text field. This doesn't have to be anything
fancy. The people using this application are computer scientists and
researchers and should be able to follow directions. i simply want to
save then the time it would take for their query to run and return them
bogus results.

TX

On Dec 3, 2:53 pm, "VK" <schools_r...@y ahoo.comwrote:
Petyr David wrote:
Just looking for the simplest. right now my perl script returns an
error messge to the user if the date string is invalid. would like to
do this before accessing the server.How do you get the date string from the user? Does she has to type it
in manually in strict mm/dd/yyyy format in a form's text field?
Dec 4 '06 #6
In comp.lang.javas cript message <ek*********@ne ws3.newsguy.com >, Sun, 3
Dec 2006 16:17:26, Matt Kruse <ne********@mat tkruse.comwrote :
>If your date format is not flexible and you don't care to support ancient
browsers, a simple regular expression can quickly test that the input is
well-formed, but can't verify that the values are valid. For that you need
to split the values out and apply some logic.
An mm/dd/yyyy string will be read correctly by new Date(S), at least in
WinXP sp2 IE6 (showing that MS's idea of localisation is inadequate).

IF future standards were to implement a reverse method DObj.toNumStr
giving a format correspondingly localised, WHICH CERTAINLY THEY SHOULD,
ISTM that your statement would no longer be true.

OK = new Date(S).toNumSt r() == S // untested, obviously.

It would be interesting to code .toNumStr() to make it give whichever of
mm/dd/yyyy and dd/mm/yyyy the current new Date(S) would use (as well as
..toNumStr(0) and .toNumStr(8601) giving yyyy-mm-dd and other arguments
giving other formats). Perhaps your library already does that; but I
don't yet see how it can be possible to do it without splitting the
values out.

function toNumStr(D) { var S
S =
LZ(D.getDate()) +'/'+ LZ(D.getMonth() +1) +'/'+ LZ(D.getFullYea r())
return (+new Date(S) == +D) ? S :
S.replace(/(.{3})(.{3})/, "$2$1") }

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v6.05 IE 6.
Web <URL:http://www.merlyn.demo n.co.uk/- w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demo n.co.uk/programs/- see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Dec 4 '06 #7
Dr J R Stockton said the following on 12/4/2006 8:25 AM:
In comp.lang.javas cript message <ek*********@ne ws3.newsguy.com >, Sun, 3
Dec 2006 16:17:26, Matt Kruse <ne********@mat tkruse.comwrote :
>If your date format is not flexible and you don't care to support ancient
browsers, a simple regular expression can quickly test that the input is
well-formed, but can't verify that the values are valid. For that you need
to split the values out and apply some logic.

An mm/dd/yyyy string will be read correctly by new Date(S), at least in
WinXP sp2 IE6 (showing that MS's idea of localisation is inadequate).

IF future standards were to implement a reverse method DObj.toNumStr
giving a format correspondingly localised, WHICH CERTAINLY THEY SHOULD,
ISTM that your statement would no longer be true.
And IF a frog had wings it wouldn't bump it's butt when it lands.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javas cript FAQ - http://jibbering.com/faq
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Dec 4 '06 #8
Petyr David wrote:
>Just looking for the simplest. right now my perl script returns an
error messge to the user if the date string is invalid. would like to
do this before accessing the server.

I'm not sure about the best...

You can use a regexp to extract the digit parts of a date. With those,
you can construct a new Date object. (Note that months start at index 0
for January.)

I found out that with the browsers I tested, this always succeeds, but
it is "corrected" to the proper calendar date, for example April 31 will
be turned into May 1.

So I could test if year, month, day are the same... but I'm guessing
that just testing the month is enough.

So here's a simple function:

function isValidDate(s) {
var m = s.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
if(!m) return false;
var d = new Date(m[3], m[1]-1, m[2]);
return m[1] == d.getMonth()+1;
}

HTH,
Bart.
Dec 4 '06 #9
In comp.lang.javas cript message
<11************ **********@73g2 000cwn.googlegr oups.com>, Sun, 3 Dec 2006
17:19:13, RobG <rg***@iinet.ne t.auwrote:
>Petyr David wrote:
>Just looking for the simplest. right now my perl script returns an
error messge to the user if the date string is invalid. would like to
do this before accessing the server.

You need to define "valid" and "simplest". The simplest test I can
think of is for 3 numbers separated by "/":

function isValidDate(dat eString){
return /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateStrin g);
}
Suggest isValidDatePatt ern or isValidDateFFFo rmat.
>But that may not be of much use - the input may not be a valid date,
e.g. 2/29/2006 will return true (as will a very large number of other
"valid" input strings).

If you want to check that the date is valid according to your required
mm/dd/yyyy, the easiest way is to firstly check the format, then that
it will generate a valid date:

function isValidDate(dat eString){
if (/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateStrin g)){
For the OP, ISTM d{2} not d{1,2}
var testDate = new Date(dateString );
After reading the next comment, = new Date(part1, part2-1, part3)
var dateBits = dateString.spli t('/');
If the RegExp is used with the match method, and parentheses are
inserted, the splitting will already have been done.
if ( dateBits[1] == testDate.getDat e() &&
(dateBits[0]-1) == testDate.getMon th() ){
Given that the RegExp establishes that MM & DD are each in 00..99, ISTM
certain that one need only test the Month. If MM is impossible,
getMonth()+1 cannot give it; if DD is out of range, the apparent Month
will be changed by -1 or +1 / +2 / +3.
>There are other methods that don't use a date object and may be
considered 'simpler' by some. Expecting mm/dd/yyyy to correctly
generate a date object when used with new Date() may be overly
dependent on browser implementations (the ECMAScript Language
specificatio n doesn't say that it must, but browsers seem to).
The optimistic will allow for the possibility that future browsers will
recognise MM/DD/YYYY or DD/MM/YYYY according to locale; and even for the
chance that, eventually, only the format chosen for the OS (mine is
YYYY-MM-DD) will be accepted. I cannot recall, and cannot now test,
whether IE4, which takes 01/02/03 as Jan 2, would take 21/02/03 as 21
Feb.

><FAQENTRY>
Should there be an FAQ on date validation?
FAQ Section 3.2 refers. If it contained a Numbered List, I could cite
the number; but a search of the FAQ for any of the words date time
dates times lastModified will find it; the entry was some while ago
altered specifically to include the singular and plural forms, to aid
searching.

My Javascript Date and Time 4 : Validation is not a FAQ, since it puts
unasked questions on the same footing as asked ones.
--
(c) John Stockton, Surrey, UK. ?@merlyn.demon. co.uk DOS 3.3, 6.20 ; WinXP.
Web <URL:http://www.merlyn.demo n.co.uk/- FAQqish topics, acronyms & links.
PAS EXE TXT ZIP via <URL:http://www.merlyn.demo n.co.uk/programs/00index.htm>
My DOS <URL:http://www.merlyn.demo n.co.uk/batfiles.htm- also batprogs.htm.
Dec 4 '06 #10

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

Similar topics

5
2023
by: lawrence | last post by:
I posted before, but have now narrowed my problem down to this method. At the start of the method, I test to make sure that I have a resource, a pointer to data returned from a database. This test is coming back true, so the next line runs, which attempts to get the next row from the dataset. This brings back nothing. On the queries I'm running right now, the first row will be fetched, but then no further rows. If I expect 20 rows back, I...
6
6650
by: Paul E Collins | last post by:
Given a string variable (form input), how can I determine whether it represents a valid integer? is_numeric is true for floats as well as integers, and is_int always fails on a string. P.
7
3070
by: Matt | last post by:
I want to test the blank data in required field. If the user enter blank data, the following code still not work. But if I test for the length of a string, it doesn't work also, any ideas?? thanks!! if (InputForm.username.value == '') alert("username is required");
6
2444
by: aron t | last post by:
Hi, I am good php programmer and want to learn asp.net. Can someone tell me what are the best and the worst features of ASP.NET? thanks
3
1033
by: ucasesoftware | last post by:
Hello, I need to test my application in a lot of configuration... What is the best solutions... i try to install Microsoft Virtual Server... but i have not success to configure it... Anyone have best solution or link to do this...
1
1482
by: tamatem | last post by:
"I have build a long sql data load script. What is the best way to do Testing of the script? I would like to automate the test!"
4
1157
by: jehugaleahsa | last post by:
Hello: What is the best way to test my methods that hit a database? I believe tests should be as automated as possible. However, I'm not sure how I can test against a database since changes will modify the (development) database. I really don't care whether my SQL does what it's supposed to do, just that I have my CommandText, CommandType and Parameters set up
8
3758
by: petesquawk | last post by:
What is the fastest and easiest way to graph data in VB.net? How do I export 2 columns of data in Vb.net, to either an excel file or to a notepad file?
2
2071
by: Johan Novak | last post by:
Hi! I'm working on a solitaire game, with a different card deck. First I create a big list with 81 elements (cards in this case), cardList. From this list, six cards are ramdomly picked and put into another list, playerCardList, and printed on the court. Once the cards are printed the player is asked to remove three cards. I would like these cards to be removed from cardList so they don't appear again. I would also like them to be put into...
0
8704
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
8623
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
9187
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8894
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
6544
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
5879
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
4637
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3071
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2361
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.