JRS: In article <
[email protected]>, dated
Tue, 15 Mar 2005 21:08:33, seen in Martin
Herrman said:
I am working on a HTML form in which a date must be entered of the form
'dd-mm-yyyy'. Now I'm looking for a script that, when the user switches to
another form field, changes e.g. 'ddmmyyyy' or 'dd-m-yy' to 'dd-mm-yyyy'.
I have searched the net using google, but only found validators that show
an error if an incorrect format is used. (and I can't write one on my own)
Does someone has such a script for me?
If you cannot trust the users to get the correct field format and
separation, can you trust the field order? And can you trust the
value??
You should be calling for an ISO 8601 format, with Y M D in that order;
it's probably also an EN and Dutch standard, and no-one uses yyyy-dd-mm.
One approach would be to consider what transformations on the input
cannot affect the date represented and bring the string nearer correct.
If the date is given as all digit, then to be unambiguous it must be
8-digit; 7 could be dmmyyyy or ddmyyyy, 6 could be dmyyyy or ddmmyy, 5
could be ddmyy or dmmyy. Actually, 4 could only be dmyy, but you might
consider that unreasonable - // ?
function FudgeDate(S) { var A, m = "-", O = '0'
if (/^(\d\d)(\d\d)(\d\d\d\d)$/.test(S))
with (RegExp) return $1 + m + $2 + m + $3
if (/^(\d)(\d)(\d\d)$/.test(S)) // ?
with (RegExp) return O + $1 + m + O + $2 + m + "20" + $3 // ?
A = S.split(/\D+/)
if (A.length!=3) return
if (+A[2]<100) A[2] = +A[2] + 2000
if (A[1].length<2) A[1] = O + A[1]
if (A[0].length<2) A[0] = O + A[0]
return A[0] + m + A[1] + m + A[2] }
There's something better than using test & $1 $2 $3 that way; but I
don't recall it at the moment.
You should also validate the date, to reject such as Feb 31st; to do
that, modify the above to return in all cases an array or object
containing the three numbers Y M D, and validate with a Date Object.
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 */ }
function ValidDate(y, m, d) { var D // m = 0..11 ; y m d integers, y!=0
with (D = new Date(y, m, d))
return getMonth()==m && getDate()==d ? D : NaN }
function ValidDate(y, m, d) { var D // m = 0..11 ; y m d integers, y!=0
with (D = new Date(y, m, d))
if (getMonth()==m && getDate()==d) return D }
respectively returning true/false, DateObject/NaN, DateObject/undefined.
(N.B. y==0 is harmless, but the result agrees with Rome rather than
Gregory)
See below.