JRS: In article <11**********************@h48g2000cwc.googlegroups .com>,
dated Wed, 11 Oct 2006 14:20:28 remote, seen in
news:comp.lang.javascript, RobG <rg***@iinet.net.auposted :
>
For validation, a simple way is to convert the incoming date string to
a date object then test if the generated date matches the string - you
only need to test 2 of the 3 bits:
var dateString = '2006-02-31';
alert( /\d{4}-\d{2}-\d{2}/.test(dateString));
Matches '1234-56-789'.
var dateBits = dateString.split('-');
var dateObj = new Date(dateString.replace(/-/g,'/'));
var isValid = ( dateBits[0] == dateObj.getFullYear()
&& dateBits[1] == (dateObj.getMonth()+1));
alert(isValid); // Shows false.
If Y M D are arbitrary Numbers, then one need only test two of the three
parts. I'd not test the Year, but Month and Day in that order.
One can use .match instead of .test, saving a .split. Although .test
seems faster, .split seems slow (crudely tested).
If the Date is known to match \d{2} it is in 0..99, so any Date error
must give the wrong month (Date=365 generally gives the right month of the
wrong year); and a Month error also gives the wrong month. Therefore one
only needs to test the Month.
var dateString = '2006-02-31';
var M = dateString.match(/^(\d{4})-(\d{2})-(\d{2})$/)
alert(!!M)
var dateObj = new Date(dateString.replace(/-/g,'/'));
var isValid = M[2] == dateObj.getMonth()+1 // && M[3] == dateObj.getDate()
alert(isValid); // Shows false.
--
© 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.