In Javascript I am trying to write the validation for a date, where the user has to select a future date and not a past date. My code seems to work only when I use a date from last month (e.g. 26/11/2011). This is my script:
<script type="text/javascript" >
function mydate()
{
var d= new Date ();
var day= d.getDate ();
var mon=d.getMonth ();
var year= d.getFullYear ();
var dateformat= day+"/"+mon+"/"+year ;
var get= document.getElementById("txt").value;
if(get >= dateformat )
{
alert ('yes valid');
}
else
{
alert('Date should greater than to date ');
}
}
</script>
1 Answer 1
You are comparing the date values as strings. This is a textual comparison not a date-wise comparison so it will pretty much never work except by coincidence. You need to parse the date value the user enters into a Date data type and do a comparison that way.
Whenever possible you should avoid writing date manipulation code yourself and try to leverage a known working solution, e.g. the jQuery UI Datepicker.