user869143
user869143

Reputation: 11

date validation in javascript

I have two text boxes, one is "From Date" and "To Date". user will enter the date in the format of "mm/dd/yyyy". Here the "To Date" is always Greater than "From Date". if not, i will alert the user "Not valide, To date is always greater than From Date".

Ex: From Date: 06/05/2011 To Date: 05/08/2011

The above statement is wrong.

       Please give your answer.

Upvotes: 0

Views: 791

Answers (2)

Annie
Annie

Reputation: 6631

First, you'll probably want to use <input type="date">, which does some validation on browsers that support it, and shows as a regular input box on browsers that don't.

For actually validating that one date is before the other, you can use a JavaScript Date Object.

var fromDate = new Date(from.value);
if (isNaN(fromDate.getTime())
  alert("Invalid From Date");
var toDate = new Date(end.value);
if (isNaN(toDate.getTime())
  alert("Invalid To Date");
if (toDate < fromDate)
  alert("Not valid, To date is always greater than From Date");

Upvotes: 1

duffymo
duffymo

Reputation: 308763

That's one way to do it. Another might be to ask if the user wishes to reverse the two.

Upvotes: 0

Related Questions