The code you are using parses date strings by just passing them into the Date
constructor. The Date
constructor expects a very specific format. I suspect it is not working because the date strings you are handing it do not conform to that format, thus Date
is not producing a valid date object which is causing the comparison function to fail.
When dealing with dates moment.js is often very helpful. In this case it could make your not only more flexible but much more readable. Moment will allow you to provide a list of acceptable date formats it will use to parse the date strings you provide it. It also provides a number of methods for comparing dates such as isAfter
.
Using these your code could be rewritten to something like this:
function validateForm() {
var acceptedFormats = ["MM-DD-YYYY", "DD-MM", "DD-MM-YYYY"],
fromDate = moment(document.getElementsByName('fdate')[0].value, acceptedFormats),
toDate = moment(document.getElementsByName('tdate')[0].value, acceptedFormats);
if (fromDate.isAfter(toDate)) { // much more readable, it's practically a sentence!
alert("To Date must be after From Date");
return false;
}
return true;
}
Something else I just noticed, your code will always fail to submit the form even if the date comparison passes. When the comparison fails you explicitly return false
which stops the form from submitting. But when the test passes you don't return anything, implicitly returning undefined
. When undefined
is passed into the submit handler ONSUBMIT="return validateForm()"
, it will be coerced into false
, also causing the form to not submit.