PDA

View Full Version : Date Validation


Goldilocks
02-23-2004, 09:56 AM
I have an html form with a date textbox. The user has to click on a javascript calendar and select the date he wants, then the textbox is automatically populated with this date in the format DD/MM/YYYY.

When the form is submitted I need to validate this textbox to make sure that the date selected is greater than or equal to the current date.

How would I go about doing this? Does anyone know of a script I can use? My boss is putting me under pressure to get this done but I can't figure it out!

Thanks in advance!

agent002
02-23-2004, 10:13 AM
Hi Goldi, I hope this script will do :)

JavaScript:
<script type="text/javascript"><!--

function validateDate(what){
var datesplit = what.split('/');
if(isNaN(datesplit[0]) || isNaN(datesplit[1]) || isNaN(datesplit[2])){
alert('Please choose a date first.');
return false;
}
var day = Number(datesplit[0]);
var month = Number(datesplit[1]);
var year = Number(datesplit[2]);
var d = new Date();
var nowday = d.getDate();
var nowmonth = (d.getMonth() + 1);
var nowyear = d.getYear();
if(nowyear < 1900){
nowyear += 1900;
}
var isvalid = true;

if(year < nowyear){
isvalid = false;
}
else if(year == nowyear && month < nowmonth){
isvalid = false;
}
else if(year == nowyear && month == nowmonth && day < nowday){
isvalid = false;
}

if(!isvalid){
alert('Please choose a valid date');
return false;
}

return true;
}
--></script>

HTML:
<form action="something.asp" method="post" onsubmit="return validateDate(document.getElementById('date').value);">
Date: <input type="text" id="date" name="date" value="DD/MM/YYYY" readonly="readonly"><br>
<input type="submit" value="Submit">
</form>

Goldilocks
02-23-2004, 10:25 AM
Thanks loads agent002, that works brilliantly!! ;)

agent002
02-23-2004, 10:29 AM
np :)