Click to See Complete Forum and Search --> : dates


swstos
04-28-2003, 01:31 AM
Hi...
i am new in javascript...
I am trying to validate the date of 2 edit boxes using yyyy/mm/dd. i am trying to execute the code below but something goes wrong.
Can please anyone tell me what is the problem???


in the form i wrote:
onSubmit="return dateformat(this);"

<script language="javascript">

function isValidDate(dateStr) {

var datePat = /^(\d{4})-?(\d{2})-?(\d{2})$/;
var matchArray = dateStr.match(datePat);
if (matchArray == null) {
alert("Please enter date as yyyy-mm-dd.");
return false;
}

year = matchArray[1];
month = matchArray[2];
day = matchArray[3];


if (month < 1 || month > 12) {
alert("Month must be between 1 and 12.");
return false;
}

if (day < 1 || day > 31) {
alert("Day must be between 1 and 31.");
return false;
}

if((month==4 || month==6 || month==9 || month==11)&& day==31) {
alert("Month "+month+" doesn't have 31 days!")
return false;
}

if (month == 2) {
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day > 29 || (day==29 && !isleap)) {
alert("February " + year + " doesn't have " + day + " days!");
return false;
}
}
return true;
}

function dateformat(dateform) {
date1 = new Date();
date2 = new Date();

if (isValidDate(dateform.firstedit.value) {
date1temp = new Date(dateform.firstedit.value );
}
else return false;
if (isValidDate(dateform.secondedit.value){
date2temp = new Date(dateform.secondedit.value );
}
else return false;
</script>

P.S. The code is not written by me ( pieces from here and there) but i am trying to execute it in order to learn.

Thanks in advance

Charles
04-28-2003, 05:18 AM
There's no need to go through all of that. The Date object constructor understands quite a few different date formats and when you try to use said object as a string JavaScript will call Date.toString(). Now, if you overwrite the native Date.toString() function then you can translate from most of the formats that your users might want to use to whatever format that you like.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Content-Script-Type" content="text/javascript">

<script type="text/javascript">
<!--
Date.prototype.toString = function () {return [this.getFullYear(), (this.getMonth() +1) < 10 ? '0' + (this.getMonth() + 1) : (this.getMonth() + 1), this.getDate() < 10 ? '0' + this.getDate() : this.getDate()].join('/')};
// -->
</script>

<form action="" onsubmit="if (this.date.value == 'NaN' || this.date.value == '') {alert('That would not appear to be a valid date.'); return false}">
<div>
<label>Date<br>
<input name="date" type="text" onchange="this.value = new Date(this.value)">
</label><br>
<input type="submit">
</div>
</form>