Eric
Eric

Reputation: 8078

Compare date in javascript

I have a custom validator that points to a Client side script to validate a textbox.

My date and time are separated into two textboxes - one with date in mm/dd/yyyy format and the other with time in hh:mm am/pm format.

I need to make sure the textboxes together are not greater than now. How can i accomplish this?

Here is what i have so far. what am i doing wrong?

function checkminutes(sender, args) {
        var txtdate = $get('<%=FormView1.FindControl("txtdate").ClientID %>');
        var txttime = $get('<%=FormView1.FindControl("txttime").ClientID %>');
        var totaltime = txtdate.value + ' ' + txttime.value;
        totaltime = Date(totaltime);
        var d = new Date();
        if (totaltime > d) {
            args.IsValid = false;
        }
        else {
            args.IsValid = true;
        }


    }

This is the answer that worked.

function checkminutes(sender, args) {
        var txtdate = $get('<%=FormView1.FindControl("txtdate").ClientID %>');
        var txttime = $get('<%=FormView1.FindControl("txttime").ClientID %>');
        var totaltime = txtdate.value + ' ' + txttime.value;
        totaltime = Date.parse(totaltime);
        var d = new Date();
        if (totaltime > d) {
            args.IsValid = false;
        }
        else {
            args.IsValid = true;
        }
    }

Upvotes: 0

Views: 571

Answers (3)

geowa4
geowa4

Reputation: 41823

Just compare the milliseconds since the epoch:

totaltime = new Date("1988/02/21 08:08");
d = new Date();
if (totaltime.getTime() < d.getTime())
    alert("Date is valid");
else
    alert("Try again, Date is not valid");

EDIT: I can't seem to get it to work when I use "am/pm", so just convert it to 24 time, and it will be fine.

Upvotes: 1

Dean J
Dean J

Reputation: 40298

You shouldn't be using javascript popups to alert the user there was a problems; they're clunky at best.

Unless you're telling the user there was a problem with AJAXy pages, just do server side validation, and your application will be slicker looking. I'm assuming if you're asking this particular question, you're not doing AJAX.

As far as serverside validation not having "the exact time", you're dealing with hours and minutes, not milliseconds.

Upvotes: 0

Josh Stodola
Josh Stodola

Reputation: 82483

Don't waste your time validating this on the client-side. It's never going to be reliable, and no matter what you are going to have to validate on the server-side anyway.

Upvotes: 0

Related Questions