Saturday, July 16, 2011

Javascript validation : Date Comparision not working

In most of the web application ,for validationJavascript is one of the must needed scripting language. There are some problem happens when you will write logical code in javascript like if condition, for loop etc.
In some case when you are working around dates you need to compare two dates. What you are doing is take value of date using Element id or Element name using getElementById or getElementsByName. and than compare it using ‘>’ or ‘<’ operator. At the end you will not get result ofcomparison as expected. Look at the below code which is almost similar to what you had written.

var date1 = document.getElementById(‘date1′).value;
var date2 = document.getElementById(‘date2′).value;
alert(“date1 is greater than date2!”);

Its because you are comparing two strings not two dates. You have to say javascript that you want to compare two dates. What you are missing is convert the value of elements in to Date object. Look at below code to convert string in to date object.Now if you will compare two values than it will compare two dates and gives correct result.

var date1 new Date(document.getElementById(‘date1′).value);
var date2 new Date(document.getElementById(‘date2′).value);
alert(“date1 is greater than date2!”);



Post a Comment

Any Questions or Suggestions ?


Professional & Experienced Freelance Developer From India, Technologist, Software Engineer, internet marketer and Open Sources Developer with experience in Finance, Telecoms and the Media. Contact Me for freelancing projects.

Enter your email address:

Delivered by FeedBurner

PHP Freelancer India - Google+