0

I'm working on a mobile website and have drop down boxes for the Month, Date and Year. I'm needing something disallow them to continue to the next step if they chose a past date. I've seen calendar controls that do this but I'm not wanting to use a calendar control. I've spent the better part of the day looking for something but haven't been able to find anything. Does anyone have something like this or know of something that maybe I'm missing?


    function date_check()
{
    var trans_date = document.form1.selectmonth.options[document.form1.selectmonth.selectedIndex].value + "-" + document.form1.selectday.options[document.form1.selectday.selectedIndex].value + "-" + document.form1.selectyear[document.form1.selectyear.selectedIndex].value;
    var d = new Date();
    var today = (d.getMonth()+1) + "-" + d.getDate() + "-" + d.getFullYear();
    if(new Date(trans_date) < new Date(today)){
        alert("The shipping date cannot be in the past, please enter a valid shipping date.");
        return false;
        }


}

This is what I came up with but it's not working. Am I missing something else? I'll leave it selected as January 1 2011 and it doesnt throw the alert.

2 Answers 2

1

Simply get the selected values from the elements in question, concatenate the values with "-" or "/" and use the Date constructor to create a date object - compare that with the current date - if it is less than the current date, then fail.

// Inside your form's validation handler ...

var year, month, day, provided_date, now = new Date();

// Remove the hours, minutes and seconds from the now timestamp
now = new Date(now.getYear(), now.getMonth(), now.getDate());

// Get your year select - document.getElementById
// or any other method you have available

year = your_year_select.options[your_year_select.selectedIndex].value;
// and so on for month and day


// Remember, month is 0 indexed in JavaScript (January is month 0)
// so make sure your dropdown values take account of this.
// Otherwise, use month - 1 here.
provided_date = new Date(year, month, day);

// if all you need to do is validate the date
return provided_date >= now;
Sign up to request clarification or add additional context in comments.

Comments

0

It sounds like you just need a validation function that creates a new date from the selected inputs and compares it to the current date. Something like:

function isFutureDate(year, month, day) {
    return (Date.parse("" + year + "-" + month + "-" + day)) - new Date() > 0;
}

Except that you'll probably need to account for the timezone shift.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.