469,631 Members | 1,297 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,631 developers. It's quick & easy.

Date Validation

I am trying to validate if an entry on a form is a date.
I have adapted code I found here
http://www.codingforums.com/archive/index.php/t-14325 as below but I can't
seem the get the results that I am expecting.

Can anyone help please

TIA
Steve
PS I'm new to javascript
-------------------------------------------------
<html>

<script TYPE = "text/javascript">
function isDate(sDate) {
var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/
if (re.test(sDate)) {
var dArr = sDate.split("/");
var d = new Date(sDate);
return d.getMonth() + 1 == dArr[0] && d.getDate() == dArr[1] &&
d.getFullYear() == dArr[2];
alert("A Date")
}
else {
alert("Not a Date")
return false;
}
}

</script>

<body>

Date: <input name=Date size=10 onBlur="javascript:isDate();">
NEXT: <input name=NEXT size=10>

</body>
</html>
Jul 23 '05 #1
14 12976
Steve Wright wrote:
I am trying to validate if an entry on a form is a date.
I have adapted code I found here
http://www.codingforums.com/archive/index.php/t-14325 as below but I can't
seem the get the results that I am expecting.

Can anyone help please

TIA
Steve
PS I'm new to javascript
-------------------------------------------------
<html>

<script TYPE = "text/javascript">
function isDate(sDate) {
var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/
I don't see any need for a regex, besides the regex is not very precise.
if (re.test(sDate)) {
var dArr = sDate.split("/");
var d = new Date(sDate);
return d.getMonth() + 1 == dArr[0] && d.getDate() == dArr[1] &&
d.getFullYear() == dArr[2];
alert("A Date")
}
else {
alert("Not a Date")
return false;
}
} COuld be rewritten:
function isDate(sDate) {
var dArr = sDate.split("/");
var d = new Date(sDate);
return d.getMonth() + 1 == dArr[0] && d.getDate() == dArr[1] &&
d.getFullYear() == dArr[2];
}
Mick


</script>

<body>

Date: <input name=Date size=10 onBlur="javascript:isDate();">
NEXT: <input name=NEXT size=10>

</body>
</html>

Jul 23 '05 #2
I take it that the function just isn't working?

maybe coz ur not sending the parameter "sDate" to it?

Date: <input name=Date size=10 onBlur="javascript:isDate(this.value);">

"Steve Wright" <wr****@wcc.govt.nz> wrote in message
news:1084246273.468034@muldoon...
I am trying to validate if an entry on a form is a date.
I have adapted code I found here
http://www.codingforums.com/archive/index.php/t-14325 as below but I can't
seem the get the results that I am expecting.

Can anyone help please

TIA
Steve
PS I'm new to javascript
-------------------------------------------------
<html>

<script TYPE = "text/javascript">
function isDate(sDate) {
var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/
if (re.test(sDate)) {
var dArr = sDate.split("/");
var d = new Date(sDate);
return d.getMonth() + 1 == dArr[0] && d.getDate() == dArr[1] &&
d.getFullYear() == dArr[2];
alert("A Date")
}
else {
alert("Not a Date")
return false;
}
}

</script>

<body>

Date: <input name=Date size=10 onBlur="javascript:isDate();">
NEXT: <input name=NEXT size=10>

</body>
</html>

Jul 23 '05 #3
"Steve Wright" <wr****@wcc.govt.nz> writes:
I am trying to validate if an entry on a form is a date.
I have adapted code I found here
http://www.codingforums.com/archive/index.php/t-14325 as below but I can't
seem the get the results that I am expecting.
That is, as a bug report, no better than "it doesn't work".
To be a usefull bug report, it should tell us *what* you are expecting,
as well as what you get.
PS I'm new to javascript
As good a time as any to learn :)
-------------------------------------------------
Remember the DOCTYPE. It is required for valid HTML, and its absence
or presence can change the behavior of some browsers.
function isDate(sDate) {
var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/
You are matching against the format "mm/dd/yyyy". That is, iirc, the
US notation for dates, and isn't used much elsewhere. If you plan on
using it on a public web page where peopl of other nationalities
can use it, you should consider using the international date form:
"yyyy-mm-dd".
if (re.test(sDate)) {
var dArr = sDate.split("/");
var d = new Date(sDate);
Here you are assuming that the Date constructor reads the string as a
US date. It's plausible, but not guaranteed.
return d.getMonth() + 1 == dArr[0] && d.getDate() == dArr[1] &&
d.getFullYear() == dArr[2];
Here you compare integers to strings. The comparison is, luckily,
converting the strings to numbers before comparing, so "08"==8 gives
the correct result.
alert("A Date")
This line is right after a return statement. It cannot be reached,
so you will never see an alert saying "A Date". The function will
just have returned true or false.

Is this the result you are not expecting? Or is something else wrong?
(See, it's hard to help you when you aren't explicit about the problems!)

Date: <input name=Date size=10 onBlur="javascript:isDate();">

^^^^^^^^^^^

This label is not needed. The content of an intrinsic event handler
like "onblur" is automatically a script. The exact language is
determined by the meta element (which you whould include):
<meta http-equiv="Content-Script-Type" content="text/javascript">
but all current browsers default to Javascript (or equivalent) if
not content-script-type is specified.

Also, you are not giving an argument to the isDate function. You
should write:
onblur="isDate(this.value);"
(Or, preferably, use "onchange" instead of "onblur" ... there is no
need for alarming again if you haven't changed anything.)
Here is another date test:
---
function isDate(sDate) { // m[m]/d[d]/yyyy format
var match = sDate.match(/^(\d\d?)\/(\d\d?)/(\d{4})$/);
if (!match) { return false; }
var yr = Number(match[3]);
var mt = Number(match[1]);
var da = Number(match[2]);
var d = new Date(yr,mt-1,da);
return (d.getMonth()+1 == mt && d.getDate() == da);
}

function testAndAlert(sDate) {
if (isDate(sDate)) {
alert("A date");
} else {
alert("Not a date!");
}
}
---
Let the isDate function just test for being a date, and then alert
based on the result of that. It's easier to manage than to put
specific alerts into a general purpose function.
You can use the above funcion as:

<input type="text" onchange="testAndAlert(this.value);">

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #4
JRS: In article <1084246273.468034@muldoon>, seen in
news:comp.lang.javascript, Steve Wright <wr****@wcc.govt.nz> posted at
Tue, 11 May 2004 15:31:13 :
I am trying to validate if an entry on a form is a date.
I have adapted code I found here
http://www.codingforums.com/archive/index.php/t-14325 as below but I can't
seem the get the results that I am expecting.
First, therefore, we have to guess what results you are expecting.
function isDate(sDate) {
var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/
if (re.test(sDate)) {
var dArr = sDate.split("/");
var d = new Date(sDate);
return d.getMonth() + 1 == dArr[0] && d.getDate() == dArr[1] &&
d.getFullYear() == dArr[2];
alert("A Date")
}
else {
alert("Not a Date")
return false;
}
}

If you had sought information in the FAQ of this newsgroup, rather than
by a Web search, all should have been well.

Code should be indented to show the intended, or actual (ideally, both)
structure.

A return statement returns; it does not just, as Delphi's Result, set a
result for later use. Therefore, that alert("A Date") cannot be
executed.

The second alert should read "Wrong pattern"; you may need a different
alert for a string such as "22/22/2222".

It is better to require \d\d rather than \d{1,2}; laxity encourages
slovenly thinking.

You yourself might write Christmas as 25/12/2004. But javascript is of
alien origin, and expects 12/25/2004 for that. So does the code, as can
be seen by inspecting use of DArr.

It is better still, if your data-enterers are intelligent, to ask for an
ISO 8601 style date, which no-one can mis-understand.
That code, laid out for readability and for not being wrapped by a
newsreader (as yours might have been), becomes

function isDate(sDate) {
var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/
if (re.test(sDate)) {
var dArr = sDate.split("/");
var d = new Date(sDate);
return d.getMonth() + 1 == dArr[0] &&
d.getDate() == dArr[1] && d.getFullYear() == dArr[2];
alert("A Date")
}
else {
alert("Not a Date")
return false;
}
}
That code fails for years before A.D. 100 <G>.

One should not (usually) just check whether a string is a valid date;
one should test whether it will be validly interpreted. Most Americans,
faced with "25/12/2004", will think "Christmas, but foreign"; but
Javascript believes that to mean 2006 January 12th. However, faced with
11/05/2004, they will think of Nov 5th rather than May 11th (it's still
late Autumn, though); and so will javascript.

It seems better to use the tests to set a variable OK, and end up by
returning that; use if (!OK) { /grumble/ }

If that's not enough, please re-ask listing the strings given, the
results expected, and the results obtained.

See <URL:http://www.merlyn.demon.co.uk/js-date4.htm#DVal>

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #5
JRS: In article <hd**********@hotpop.com>, seen in
news:comp.lang.javascript, Lasse Reichstein Nielsen <lr*@hotpop.com>
posted at Tue, 11 May 2004 18:38:19 :
function isDate(sDate) {
var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/


You are matching against the format "mm/dd/yyyy". That is, iirc, the
US notation for dates, and isn't used much elsewhere.

It is the US format, the UK format, and if the DOS 5 manual is to be
trusted, it is also used in "Latin America", BE, ES, IT, BR, and in
international English. But not DK, which they say uses dd-mm-yyyy.

I don't know what the NZ govt uses; but if it uses #[#]/#[#]/####, it
should use DD/MM/YYYY.

The OP forgot to provide a parameter; if a function behaves inscrutably,
it is always well to check, with a temporary alert, that it is actually
receiving something appropriate.

I thought BR was in Latin America!

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demon.co.uk/programs/> - see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Jul 23 '05 #6
JRS: In article <q5********************@twister.nyroc.rr.com>, seen in
news:comp.lang.javascript, Mick White <mw******@BOGUSrochester.rr.com>
posted at Tue, 11 May 2004 11:49:42 :
var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/
I don't see any need for a regex, besides the regex is not very precise.


It's more precise than not using one.
COuld be rewritten:
function isDate(sDate) {
var dArr = sDate.split("/");
var d = new Date(sDate);
return d.getMonth() + 1 == dArr[0] && d.getDate() == dArr[1] &&
d.getFullYear() == dArr[2];
}


For me, in MSIE4, that appears to accept all valid dates after AD99.
but it also gives true for isDate("0006/+030/003333")
but not isDate("0006/+030/0003333")

If a "date" is in a strange form, one may prefer not to trust it.

By using a simple, and therefore reliable, RegExp, one avoids thinking
about what new Date() may do with a strange string.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demon.co.uk/programs/> - see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Jul 23 '05 #7
Dr John Stockton wrote:

<snip>

It is better still, if your data-enterers are intelligent, to ask for an
ISO 8601 style date, which no-one can mis-understand.


Is that to imply that users that use, and understand, a non-ISO 8601
style date are "un-intelligent"? I hope you are not that naive and
mis-guided by your apparent hatred of the US.

To ensure a date is "valid" is very simple, and employed *very* widely.
Even though you, and I alike, can type the date quicker, the problems
with date validation is very apparent by the number of sites that use
select lists (labeled for day, month, and year) on the web.

So, if I have three select lists, properly labeled, can you please tell
me how I can get an invalid date if the actual date is assembled on the
server? The only major problem associated with that approach is the
year, which a text input can be used for.
--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq/
Jul 23 '05 #8
Here's what I eventually came up with.
I ame sure that it can be improved upon but it does what I want

Steve
--
<script language = "javascript">
// d[d]/m[m]/yyyy format
function isDate(sDate) {
var match = sDate.match(/^(\d\d?)\/(\d\d?)\/(\d{4})$/);
if (match == null || match == 'undefined') {
return false;
}
var da = Number(match[1]); // day
var mt = Number(match[2]); // month
var yr = Number(match[3]); // year
var d = new Date(yr,mt-1,da);
return (d.getDate() == da && d.getMonth()+1 == mt && d.getFullYear() ==
yr);
}

function testAndAlert(sDate) {
if (isDate(sDate)) {
window.status = 'Date Valid';
} else {
alert("Please enter a valid date in dd/mm/yyyy format!");
}
}

</script>
--
"Steve Wright" <wr****@wcc.govt.nz> wrote in message
news:1084246273.468034@muldoon...
I am trying to validate if an entry on a form is a date.
I have adapted code I found here
http://www.codingforums.com/archive/index.php/t-14325 as below but I can't
seem the get the results that I am expecting.

Can anyone help please

TIA
Steve
PS I'm new to javascript
-------------------------------------------------
<html>

<script TYPE = "text/javascript">
function isDate(sDate) {
var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/
if (re.test(sDate)) {
var dArr = sDate.split("/");
var d = new Date(sDate);
return d.getMonth() + 1 == dArr[0] && d.getDate() == dArr[1] &&
d.getFullYear() == dArr[2];
alert("A Date")
}
else {
alert("Not a Date")
return false;
}
}

</script>

<body>

Date: <input name=Date size=10 onBlur="javascript:isDate();">
NEXT: <input name=NEXT size=10>

</body>
</html>

Jul 23 '05 #9
There are a lot of good answers on this thread but personally I think
javascript itself is a better date validator.

function isDate(sDate) {
var scratch=new Date(sDate);
if (scratch.toString()=="NaN" || scratch.toString()=="Invalid Date") {
alert("Not a Date");
return false;
} else {
return true;
}

Javascript's date parser is actually very robust and powerful and able
to hande 1/20/2004 as well as January 20 2004. IE returns NaN (not a
number) when it can't figure out a date, Mozilla (gekko engine) returns
Invalid Date.

--
-------------
http://www.hunlock.com -- DHTML for the rest of us.
Jul 23 '05 #10
Randy Webb <hi************@aol.com> writes:
Dr John Stockton wrote:

<snip>
It is better still, if your data-enterers are intelligent, to ask
for an ISO 8601 style date, which no-one can mis-understand.
Is that to imply that users that use, and understand, a non-ISO 8601
style date are "un-intelligent"?
I can't read it that way, even if I try.

The logical conclusion from that statement must be that:

1) all intelligent users can understand ISO 8601 dates, and, since
intelligence wouldn't be mentioned otherwise, some non-intelligent
users might not understand ISO 8601. That is always a danger of using
non-local date formats.

2) Some users can misunderstand a non-ISO 8601 date (and probably even
some intelligent users).

So really, it's: All intelligent users can understand ISO 8601 dates.
No other combination is safe.
So, if I have three select lists, properly labeled, can you please
tell me how I can get an invalid date if the actual date is assembled
on the server?


Using select elements doesn't prevent the 30th of February. You need
extra logic for that.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #11
"Steve Wright" <wr****@wcc.govt.nz> writes:
Here's what I eventually came up with.
I ame sure that it can be improved upon but it does what I want
It can be improved, slightly.
<script language = "javascript">
The type attribute is required by HTML 4. Make this
<script type="text/javascript">
and it will both work and be valid HTML (no reason no to :)
if (match == null || match == 'undefined') {
You don't mean "'undefined'", which is a string literal, but the
variable "undefined". However, that variable is undefined in IE 5.
Since both of the values "undefined" and "null" convert to booleans
as false, and all arrays convert to true, this test is safer:
if (!match) {

var d = new Date(yr,mt-1,da);
Notice that if 0<=yr<100, the Date constructor adds 1900 to the date ...
return (d.getDate() == da && d.getMonth()+1 == mt && d.getFullYear() ==
yr);


.... making the getFullYear test fail.

You can completely drop the test for getFullYear. If the arguments to
Date are not a valid date, then at least two of date/month/year will
be wrong when you test, so testing any two is sufficient to guarantee
that the data was valid. Since getFullYear doesn't exist in all older
browsers, it would be the obvious one to drop.

If you want to use the test for years between 0 and 99, you'll need to
do some changes anyway.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #12
JRS: In article <xu********************@comcast.com>, seen in
news:comp.lang.javascript, Randy Webb <hi************@aol.com> posted at
Tue, 11 May 2004 23:35:51 :
Dr John Stockton wrote:
It is better still, if your data-enterers are intelligent, to ask for an
ISO 8601 style date, which no-one can mis-understand.


Is that to imply that users that use, and understand, a non-ISO 8601
style date are "un-intelligent"? I hope you are not that naive and
mis-guided by your apparent hatred of the US.


My objections are to stupidity; the US has not yet achieved a monopoly
of that. Indeed, it probably never will; but it shows no sign of losing
its majority, and therefore must expect to provide the best examples.

But you, who give no overt indication of location (but must be US, since
no-one else much dislikes a dislike of typical American habits), have
just provided a fine illustration of the problem; in saying that no-one
can misunderstand an ISO-style date, I in fact compliment (albeit
perhaps wrongly) Americans on their versatility. That implies only that
the non-intelligent, whoever they may be, *may* not be able to enter
ISO-style dates correctly.

It's a pity that the Americans did not choose - AIUI, they could well
have done so - to speak German; then, those learning English would have
been taught to do so professionally, and would at least have been able
to read it reliably. And, in that case, I'd also have been taught
German for more than a dozen lessons, which, as it has turned out, would
have been useful.

Anyone, of course, can mis-understand a US- (or UK-) style date; even an
intelligent American may well misunderstand a US date, if she believes
the date to have been written by a foreigner.

The answer to your question is therefore "No" to "to imply". If you had
been asking about that, it would have been "Yes" to "use" and "No" to
"understand", where "use" implies a free choice.

To ensure a date is "valid" is very simple, and employed *very* widely.
Even though you, and I alike, can type the date quicker, the problems
with date validation is very apparent by the number of sites that use
select lists (labeled for day, month, and year) on the web.
That is probably because programmers like programming, and hence prefer
complex solutions - especially if paid for the amount of code, rather
than the quality of the result.
So, if I have three select lists, properly labeled, can you please tell
me how I can get an invalid date if the actual date is assembled on the
server? The only major problem associated with that approach is the
year, which a text input can be used for.


You can get February 30th or 31st, or 29th in a common year, or Apr Jun
Sep Nov 30th - unless the date boxes are entered in Y M D order and the
D list length depends on the Y M selections; that is shown in my js-
date6.htm. The code there could perhaps be improved or shortened; but I
doubt whether it can be made shorter or simpler than a full validation
of a date string of specified format.


****
MAINLY TO STEVE :

Number(match[1]) etc. are fine; but +match[1] is sufficient; see
in the FAQ.

After checking by RegExp, there is no need to test all 3 of da my yr ;
without a RegExp check, I'm unsure whether all 3 need testing.

But a RegExp, or other capable check, should be used : consider
022/12/2004 - 22 Dec is a fine date, but there's no way of telling
whether the user started to enter a date such as 02/..., corrected
himself, and continued on the basis that 022 means 22, or whether he
meant 02/... and did not notice keyboard stutter.

For similar reasons, IMHO \d\d or \d{2} is safer than \d\d? or \d{1,2} .

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demon.co.uk/programs/> - see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Jul 23 '05 #13
Lasse Reichstein Nielsen wrote:
So, if I have three select lists, properly labeled, can you please
tell me how I can get an invalid date if the actual date is assembled
on the server?

Using select elements doesn't prevent the 30th of February. You need
extra logic for that.


So its easier to determine a "valid date" than it is to determine the
days in February? I don't see it.
--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq/
Jul 23 '05 #14
JRS: In article <y8**********@hotpop.com>, seen in
news:comp.lang.javascript, Lasse Reichstein Nielsen <lr*@hotpop.com>
posted at Wed, 12 May 2004 18:32:37 :
var d = new Date(yr,mt-1,da);
Notice that if 0<=yr<100, the Date constructor adds 1900 to the date ...

If you want to use the test for years between 0 and 99, you'll need to
do some changes anyway.

I expect that with (d = new Date(0)) setFullYear(yr, mt-1, da)
will suffice, or at least help. It does require "Full", though. The 0
is, I think, not essential.

Of course, before about M1.6 the Julian Calendar should be used - js-
date8.htm

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demon.co.uk/programs/> - see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Jul 23 '05 #15

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

30 posts views Thread by Dr John Stockton | last post: by
reply views Thread by Brian Conway | last post: by
7 posts views Thread by Paul | last post: by
12 posts views Thread by Diego | last post: by
1 post views Thread by Brendan Reynolds | last post: by
3 posts views Thread by =?Utf-8?B?Q2hyaXM=?= | last post: by
2 posts views Thread by John Smith | last post: by
Stang02GT
5 posts views Thread by Stang02GT | last post: by
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.