0

I have two date fields. One field is from date and second one is to date.
While the cursor moving from second date field to submit button, I have to compare the two dates.
if from date greater than to date it has to display error and has to empty the field and has to focus.
For example:
My date format is:MM-DD-YYYY
first date is:08-10-2015 and secondate is:08-15-2015 , if the date is like this it has to do nothing.
Suppose, if is in reverse like,first date is:08-15-2015 and secondate is:08-10-2015, it has to display error. how to do ?

3
Contributors
2
Replies
6
Views
2 Years
Discussion Span
Last Post by Taywin
0

If you are dealing with plan text, split the string using "-" as delimiter (or use it as regEX).

var date1 = "08-15-2015";
var date2 = "08-10-2015";
var mdy1 = date1.split("-");  // should get ["08", "15", "2015"]
var mdy2 = date2.split("-");  // should get ["08", "10", "2015"]

Then compare each portion of the result. If any of the portion is unexpected, return false. The issue here (from your String example) is that the order of array content is NOT applicable to go through a loop because of the date format -- mm-dd-yy. You have to manually compare them in order.

// year
if (Number(mdy1[2])>Number(mdy2[2])) { return false; }
else if (Number(mdy1[2])<Number(mdy2[2])) { return true; }

// year is equal, compare month
if (Number(mdy1[0])>Number(mdy2[0])) { return false; }
else if (Number(mdy1[0])<Number(mdy2[0])) { return true; }

// month is equal, compare day
if (Number(mdy1[1])>Number(mdy2[1])) { return false; }  // day
return true;

The Number() function is used to ensure that the comparison is number to number, but not check for not-a-number. This script does not validate inputs. You must always validate input or you could either get unexpected result or the script breaks.

PS: The return value indicates whether the first date is before or the same as the second date.

Edited by Taywin

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.