-1

I have a entry form in which I can allow today's date and future date but can't allow yesterday and previous days. I need to do this validation using java-script on client side.

var futuredate = new Date($("#Deadline").val());
var today = new Date();

This gives me date with time. Mon Nov 04 2013 00:00:00 GMT+0530 (India Standard Time) I want only date to compare as when user enters today's date entered date is : Fri Apr 05 2013 00:00:00 GMT+0530 (India Standard Time) current date from new Date():Fri Apr 05 2013 16:53:00 GMT+0530 (India Standard Time)

I tried using sethours() it worked fine for current month, but as it converts date in number it creates problem when date entered is of previous or any before month. for example: the date entered date is 23/3/2013 and today is 5/4/2013 it considers the entered date as valid.

var futuredate = new Date($("#Deadline").val()).setHours(0, 0, 0, 0);
var today = new Date().setHours(0, 0, 0, 0);
if (futuredate >= today) {
   alert("Valid");
}
else if (futuredate < today) {
   alert("InValid");
}
Sparky
  • 98,165
  • 25
  • 199
  • 285
blue
  • 568
  • 3
  • 10
  • 30

2 Answers2

2

Try the following, it uses a little function to parse your datestring into a date object before using setHours(). This will work if your string is in format dd/mm/yyyy or dd-mm-yyyy.

var futuredate = parseDate(input).setHours(0, 0, 0, 0);
var today = new Date().setHours(0, 0, 0, 0);
if (futuredate >= today) {
   alert("Valid");
}
else if (futuredate < today) {
   alert("InValid");
}

//function to return a date object from the date string passed to it
function parseDate(input) {
    var parts = input.match(/(\d+)/g);
    return new Date(parts[2], (parts[1]-1), parts[0]);
}
Mark Walters
  • 12,060
  • 6
  • 33
  • 48
0

just split the date and set the date function concept .using this way we can easily compare the the date

 var a =futuredate.split('/');
 var b =today.split('/');
 var date1 = new Date(a[2],a[1],a[0]);
 var date2 = new Date(b[2],b[1],b[0]);

if (date1 >= date2) {
   alert("Valid");
}
else if (date1 < date2) {
   alert("InValid");
}
tamilmani
  • 591
  • 6
  • 13