date comparison

They have: 330 posts

Joined: Apr 2000

I have a textbox which should be filled in with a date value. I don't want the user using any date later than today. I have the ability of using ASP to change the date on the backed and now the customer wants to have an alert explaining to the rep what the problem is.

How would I compare a date in a textbox to today using javascript?

Thanks.

They have: 447 posts

Joined: Oct 1999

<script language=javascript>

function CheckDate(txtField) {
// assumes input of MM/DD/YYYY
var dateString = txtField.value;

// trim whitespace
dateString = dateString.replace(/^ */,"");
dateString = dateString.replace(/ *$/,"");

if(!/^\d{2}\/\d{2}\/\d{4}$/.test(dateString)) {
alert("Date must be in the format MM/DD/YYYY");
return;
}

var mm = dateString.substring(0,2);
var dd = dateString.substring(3,5);
var yy =dateString.substring(6);

var now = new Date();
now.getDate();
var date = new Date(yy,mm-1,dd);

if(date.getTime() > now.getTime()) {
alert("The date cannot be in the future.");
return;
}
}

</script>

<FORM>
<INPUT TYPE=text ONCHANGE="CheckDate(this)">
</FORM>
'

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.