focus and select

0 views
Skip to first unread message

Rob

unread,
Mar 29, 2004, 7:32:27 AM3/29/04
to
Hi there!

After validating a date in a input box, I want to alert that the date is not
correct and select the input in the box.

function checkdate_van()
{
flag = true;
dt = vandatum.value;
if (dt.length == 10)
{
if (dt.substring(2,3) != '-' || dt.substring(5,6) != '-') flag = false;
dy = parseInt(dt.substring(0,2));
if (dy < 1 || dy > 31) flag = false;
mt = parseInt(dt.substring(3,5));
if (mt < 1 || mt > 12) flag = false;
yr = parseInt(dt.substring(6,10));
}
else
{
flag = false;
}

if (flag==false)
{
alert('Incorrect date');
vandatum.focus();
vandatum.select();
}
}

This function works fine, only the focus and select doesn't. 'vandatum' is
input type=text, I don't use a form.

What is wrong?

Greetz,

Rob


Martin Honnen

unread,
Mar 29, 2004, 7:47:32 AM3/29/04
to

Rob wrote:

> After validating a date in a input box, I want to alert that the date is not
> correct and select the input in the box.
>
> function checkdate_van()
> {
> flag = true;
> dt = vandatum.value;

Do you get an error message here that vandatum is not defined?


> if (flag==false)
> {
> alert('Incorrect date');
> vandatum.focus();
> vandatum.select();
> }
> }
>
> This function works fine, only the focus and select doesn't. 'vandatum' is
> input type=text, I don't use a form.

If you have an <input> outside of any <form> then you need an id
attribute to access the element in most browsers:
<input type="text" id="vandatum">
then you can have
var vandatum;
if (document.getElementById) {
vandatum = document.getElementById('vandatum');
if (vandatum) {
...
}
}
Accessing the element directly as a variable will only do in IE and
maybe some other browsers copying IE's object model
--

Martin Honnen
http://JavaScript.FAQTs.com/

Andrew Urquhart

unread,
Mar 29, 2004, 7:50:31 AM3/29/04
to
Rob wrote:
> Hi there!
>
> After validating a date in a input box, I want to alert that the date
> is not correct and select the input in the box.
>
<script cut/>

>
> This function works fine, only the focus and select doesn't.
> 'vandatum' is input type=text, I don't use a form.
>
> What is wrong?

1. It's not very good at validating dates since not all dates are
formatted in the way that your script needs them to be. You could try:
http://www.merlyn.demon.co.uk/js-date4.htm#VID although I'm surprised to
see that there isn't a dedicated <FAQENTRY> on validating dates.

2. Use a form. Your script may work in IE but not likely for other
browsers, it's poor markup and has other side effects besides your
script not functioning.
--
Andrew Urquhart
- FAQ: http://jibbering.com/faq
- Archive: http://groups.google.com/groups?group=comp.lang.javascript
- Reply: www.andrewu.co.uk/contact/


Dr John Stockton

unread,
Mar 29, 2004, 2:27:07 PM3/29/04
to
JRS: In article <c4952r$atl$1...@news1.tilbu1.nb.home.nl>, seen in
news:comp.lang.javascript, Rob <legedoos__...@hotmail.com> posted
at Mon, 29 Mar 2004 14:32:27 :

>After validating a date in a input box, I want to alert that the date is not
>correct and select the input in the box.
>
>function checkdate_van()

Needs // dd-mm-yyyy to help readers.
YYYY-MM-DD is preferable (ISO 8601), and the
Dutch should be smart enough to use it.

>{
> flag = true;
> dt = vandatum.value;
> if (dt.length == 10)
> {
> if (dt.substring(2,3) != '-' || dt.substring(5,6) != '-') flag = false;

dt.charAt is more direct.

> dy = parseInt(dt.substring(0,2));

Should fail on the 8th and 9th of the month, FAQ 4.12

> if (dy < 1 || dy > 31) flag = false;
> mt = parseInt(dt.substring(3,5));

Should fail for Aug & Sept, FAQ 4.12

> if (mt < 1 || mt > 12) flag = false;
> yr = parseInt(dt.substring(6,10));
> }
> else
> {
> flag = false;
> }
>
> if (flag==false)

You should write that as if (!flag)

> {
> alert('Incorrect date');
> vandatum.focus();
> vandatum.select();
> }
>}


For validation, see <URL:http://www.merlyn.demon.co.uk/js-valid.htm> and
its links.

--
© 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.

Dr John Stockton

unread,
Mar 29, 2004, 2:49:57 PM3/29/04
to
JRS: In article <FWU9c.93$B_1...@newsfe1-gui.server.ntli.net>, seen in
news:comp.lang.javascript, Andrew Urquhart <re...@website.in.sig> posted
at Mon, 29 Mar 2004 13:50:31 :

>1. It's not very good at validating dates since not all dates are
>formatted in the way that your script needs them to be. You could try:
>http://www.merlyn.demon.co.uk/js-date4.htm#VID although I'm surprised to
>see that there isn't a dedicated <FAQENTRY> on validating dates.

Searching the FAQ for date or time or dates or times will find the
preantepenultimate entry in Section 3.2, though.

Are you volunteering to distil a FAQ entry from available information?

BTW, #VID is not the best place to start reading that page; IMHO, the OP
should start no lower than #TDVal . There's also #ISO . Granted,
probably only #VID handles dd-mm-yyyy, but the others could easily be
changed.

--
© 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.

Andrew Urquhart

unread,
Mar 29, 2004, 5:44:26 PM3/29/04
to
Dr John Stockton wrote:

> Andrew Urquhart wrote:
>> I'm surprised to see that there isn't a dedicated < FAQENTRY >
>> on validating dates.
>
> ... Are you volunteering to distil a FAQ entry from available
> information?

Whilst I've contributed to FAQ entries before, I think someone with more
experience of the pitfalls of date validation would be better suited to
the task. Ergo, yourself!

Dr John Stockton

unread,
Mar 30, 2004, 12:31:46 PM3/30/04
to
JRS: In article <rD1ac.97$W37...@newsfe1-gui.server.ntli.net>, seen in

news:comp.lang.javascript, Andrew Urquhart <re...@website.in.sig> posted
at Mon, 29 Mar 2004 23:44:26 :

>Dr John Stockton wrote:
>> Andrew Urquhart wrote:
>>> I'm surprised to see that there isn't a dedicated < FAQENTRY >
>>> on validating dates.
>>
>> ... Are you volunteering to distil a FAQ entry from available
>> information?
>
>Whilst I've contributed to FAQ entries before, I think someone with more
>experience of the pitfalls of date validation would be better suited to
>the task. Ergo, yourself!


But code is more trustworthy when checked by non-authors! And I can
only test on one browser, whereas others are better able to assess
compatibility.

It seems clear that one should use a RegExp to check and split a date
string, then load those into a Date Object and verify two of Y M D. But
which two? Use of M & D seems better for validation, since the
questions of whether getFullYear is available and what about the First
Century are dodged. But for conversion to an Object, ISTM that
getFullYear is needed, checking Y and one of M, D.


For the FAQ, ISO date order can be used; adapting for another order is
trivial.

Field separators can be required; adapting to their absence is trivial.

Better not to compel the ISO separator, '-', since others are common and
may reasonably be preferred, and adapting to compulsion is trivial.

Questions for a FAQ-worthy solution :-

In the code, should one permit any non-digit character(s) as separators,
or a specific set, perhaps { - / . }?

Should the second separator be given the same freedom, or should it
exactly match the first?

Should any specific number of digits be required for the D, M, and
especially Y fields?

Should [Y, M, D] or a Date Object or something else be returned?

How about years below 100? - one should consider, carefully, whether
0052-02-29 is going to be shown as valid [a].

Should the RegExp be written to require that the first digit is non-
zero?


Here are a couple of possibilities -

function GetYMDdateD(Q) { var y, d, D, Undef // year>99
if ((D = /^(\d+)(\D)(\d\d)(\2)(\d\d)$/.exec(Q)) != null)
with (D = new Date(y=+D[1], D[3]-1, d=+D[5]))
if (getFullYear()==y && getDate()==d) return D
return Undef }

function ISODateValue(Q) { var B, D=0
B = /^(\d{4})-(\d\d)-(\d\d)$/.test(Q) // Split Q into $1 $2 $3
if (B) with (RegExp) { // If pattern OK, test Y M D numbers
D = new Date($1, $2-1, $3) // $1 $2 $3 = Y M D
B = ((D.getMonth()==$2-1) && (D.getFullYear()==$1)) // Y M D OK?
}
return [B, D] /* [Valid, DateObject] end ISODateValue */ }


[a] Risk of being considered as octal, thus AD 42, non-leap.

Andrew Urquhart

unread,
Mar 31, 2004, 10:03:58 AM3/31/04
to
Dr John Stockton wrote:
<trim />

> It seems clear that one should use a RegExp to check and split a date
> string, then load those into a Date Object and verify two of Y M D.
> But which two? Use of M & D seems better for validation, since the
> questions of whether getFullYear is available and what about the First
> Century are dodged. But for conversion to an Object, ISTM that
> getFullYear is needed, checking Y and one of M, D.
<trim />

The data for the day, month and year may not be a single string - the
data may have been input via 3 distinct form controls, or via some form
of GUI, etc. Therefore there should be a separation between determining
what data is day, month or year and the actual date validation part.

A stricter definition of a "valid date" is needed since in some browsers
"Wed, 38 Mar 2004 14:05:30 UTC" is a valid date. E.g.: IE returns "Wed,
7 Apr 2004 14:05:30 UTC ", but Opera ignores the string and creates a
current date as if invoked as new Date().

Should other date-time units be involved? Comparing month and year
values from a Date object with the constructor argument values of month
and year is no good if a date was created with day=10, month=10,
year=2004 and hours=24.

Obviously a RegExp would be unable to cope with (MM/DD/YY vs. DD/MM/YY
vs. YY/MM/DD) without some additional knowledge of the date format being
used. This could lead to an explanation of best practice in
international date formats both in processing and in GUIs. E.g.
processing should always use an international standard date format (IS0
8601 or RFC0822/RFC1123) but GUIs should be written to avoid such
confusion by not allowing the user to specify multiple values in the
same input - i.e. use several select-one controls or text inputs, etc.

The getYear/getFullYear issue is awkward, but perhaps it is better that
a validation script fails if getFullYear is not available rather than
the possibility of falsely compensating.

> Questions for a FAQ-worthy solution :-
>
> In the code, should one permit any non-digit character(s) as
separators,
> or a specific set, perhaps { - / . }?

I vote for any non-digit assuming the input into the validation function
is a string, but I prefer separate D, M, Y input arguments.

> Should the second separator be given the same freedom, or should it
> exactly match the first?

I wouldn't make this distinction, e.g. 01d02m03y

> Should any specific number of digits be required for the D, M, and
> especially Y fields?

I vote for D or M as (\d{1,2}) but Y as \d+, since no theoretical
assumption can be made as to the year required. 54 is of course a valid
year and it wouldn't seem wise to second-guess the user and
'auto-correct' to 2054. It would be wise to question this in a GUI, but
seemingly not in the date validation function.

> Should [Y, M, D] or a Date Object or something else be returned?

ISTM that a Boolean is the expected output of a function that is
designed to test if a date is valid or not.

> How about years below 100? - one should consider, carefully, whether
> 0052-02-29 is going to be shown as valid [a].

If the validation function is documented as requiring decimal integers
only, this would get around the requirement to deal with octal.

> Should the RegExp be written to require that the first digit is non-
> zero?

I can't see any requirement for that, but that's largely due to
considering octal values as invalid input in the previous answer.

Dr John Stockton

unread,
Apr 1, 2004, 5:25:31 PM4/1/04
to
JRS: In article <J3Bac.315$gx5...@newsfe1-gui.server.ntli.net>, seen in

news:comp.lang.javascript, Andrew Urquhart <re...@website.in.sig> posted
at Wed, 31 Mar 2004 16:03:58 :

>Dr John Stockton wrote:
><trim />
>> It seems clear that one should use a RegExp to check and split a date
>> string, then load those into a Date Object and verify two of Y M D.
>> But which two? Use of M & D seems better for validation, since the
>> questions of whether getFullYear is available and what about the First
>> Century are dodged. But for conversion to an Object, ISTM that
>> getFullYear is needed, checking Y and one of M, D.
><trim />
>
>The data for the day, month and year may not be a single string - the
>data may have been input via 3 distinct form controls, or via some form
>of GUI, etc. Therefore there should be a separation between determining
>what data is day, month or year and the actual date validation part.

Yes/no. There should be a means of validating the tri-numeric form, and
also one for the string form. The latter can/should use the algorithm,
but not the function, of the former - because the latter can be better
written merged, and even if both are required the duplication is only
about one line.

If a Date Object is to be returned, ISTM that it should be the one used
in the validation; often the question is not whether a date string is
valid, but whether it is both valid and converted correctly.

For validating Y, M, D input, consider the following as added to the
previous post :-

function ValidDate(y, m, d) { // m = 0..11 ; y m d integers, y!=0
with (new Date(y, m, d))
return (getMonth()==m && getDate()==d) /* was y, m */ }

I believe that to be valid for the entire range of the proleptic
Gregorian astronomical calendar that a Date Object can hold, except that
the single day 0000-02-29 is spuriously failed (Years 0 to 99 map to
1900-1999, but only that day differs in existence).


>A stricter definition of a "valid date" is needed since in some browsers
>"Wed, 38 Mar 2004 14:05:30 UTC" is a valid date. E.g.: IE returns "Wed,
>7 Apr 2004 14:05:30 UTC ", but Opera ignores the string and creates a
>current date as if invoked as new Date().


That's not a date-as-I/we-meant it, though; it's an instant or a second.

For the FAQ proper, ISTM sufficient to consider a string containing Y M
D and no other significant information; and to disregard month strings
such as 'Apr'; that should be left to the Notes or a general Web site.


>Should other date-time units be involved? Comparing month and year
>values from a Date object with the constructor argument values of month
>and year is no good if a date was created with day=10, month=10,
>year=2004 and hours=24.

That's either not valid, not a date, or a special case.

>Obviously a RegExp would be unable to cope with (MM/DD/YY vs. DD/MM/YY
>vs. YY/MM/DD) without some additional knowledge of the date format being
>used. This could lead to an explanation of best practice in
>international date formats both in processing and in GUIs. E.g.
>processing should always use an international standard date format (IS0
>8601 or RFC0822/RFC1123) but GUIs should be written to avoid such
>confusion by not allowing the user to specify multiple values in the
>same input - i.e. use several select-one controls or text inputs, etc.

I tested. I am a bad typist but an average mouser; nevertheless, for me
typing a yyyy-mm-dd is substantially quicker than using drop-down lists.

But typing yyyy<tab>mm<tab>dd should be quick; the tab key is less handy
than the dash key but a bigger target. One needs to check that yyyy is
not taken incorrectly as 0.


>The getYear/getFullYear issue is awkward, but perhaps it is better that
>a validation script fails if getFullYear is not available rather than
>the possibility of falsely compensating.

Unfortunately, there's no "new FullDate ()" that believes in years
0..99. Perhaps with (D = new Date()) setFullYear(Y, M-1, D) rather
than just D = new Date() ? But it must be setFullYear; setYear gives
me today's date in 19xx for Y=xx.

>> Questions for a FAQ-worthy solution :-
>>
>> In the code, should one permit any non-digit character(s) as
>separators,
>> or a specific set, perhaps { - / . }?
>
>I vote for any non-digit assuming the input into the validation function
>is a string, but I prefer separate D, M, Y input arguments.
>
>> Should the second separator be given the same freedom, or should it
>> exactly match the first?
>
>I wouldn't make this distinction, e.g. 01d02m03y
>
>> Should any specific number of digits be required for the D, M, and
>> especially Y fields?
>
>I vote for D or M as (\d{1,2}) but Y as \d+, since no theoretical
>assumption can be made as to the year required.

You're assuming that it is after the year -1 !

Perhaps Y as [1-9]\d{2,} which removes any possibility of years before
100 and of giving 2 digits for a four-digit year.

Those who want to accept two-digit current years can add their own
century before validating.


> 54 is of course a valid
>year and it wouldn't seem wise to second-guess the user and
>'auto-correct' to 2054. It would be wise to question this in a GUI, but
>seemingly not in the date validation function.
>
>> Should [Y, M, D] or a Date Object or something else be returned?
>
>ISTM that a Boolean is the expected output of a function that is
>designed to test if a date is valid or not.

For a validator, agreed; but not for a date input routine that also
checks validity.


>> How about years below 100? - one should consider, carefully, whether
>> 0052-02-29 is going to be shown as valid [a].
>
>If the validation function is documented as requiring decimal integers
>only, this would get around the requirement to deal with octal.

But not that of determining whether 0052 is taken as being whichever of
decimal 52 & 42 was not intended!


>> Should the RegExp be written to require that the first digit is non-
>> zero?
>
>I can't see any requirement for that, but that's largely due to
>considering octal values as invalid input in the previous answer.

By having the first digit non-zero AND requiring at least three digits,
one renders years 0-99 unavailable rather than inconvenient!

Reply all
Reply to author
Forward
0 new messages