0

The below function is not validating if keeps skipping when it gets to the day else if statement I am trying to prevent the user entering a future date.

I have month and year working. However day is not working. Also user should be able to enter 4 March 2016 but not > 5 march 2016

  function fieldDateNotInFutureValidator(prefixPartDateInput){
    if(event.type == "submit") {
        console.log(event.type);

        var selectedDay = $("#proof_of_address_form\\:input-"+prefixPartDateInput+"-day").val();
        var selectedMonth = $("#proof_of_address_form\\:input-"+prefixPartDateInput+"-month").val();
        var selectedYear = $("#proof_of_address_form\\:input-"+prefixPartDateInput+"-years").val();
        var valid = false;

        var today = new Date();
        var currentDay = today.getDate().toString();
        var currentMonth = today.getMonth() + 1;
        var thisMonth = currentMonth.toString();
        var currentYear = today.getFullYear().toString();
        console.log(today,currentDay, thisMonth, currentYear);


        if (selectedYear < currentYear) {
            valid = true;
        } else if (selectedYear == currentYear && selectedMonth <= thisMonth) {
            valid = true;
        } else if (selectedDay > currentDay) {
            return false;
        }
        else {
            valid = false;
        }
        return valid;
    }
    return true;
}
user3433451
  • 71
  • 1
  • 4
  • 2
    It's possible to compare dates via operators. See http://stackoverflow.com/questions/492994/compare-two-dates-with-javascript – dex Mar 04 '16 at 15:24
  • 1
    the last else if is not doing anything, it will return false either way. I think the logic is a bit lacking. why don't u create a new date obj and check if the selected date is prior to it? the logic is much easier. something like if(selectedDate < new Date()) return true... – LiranBo Mar 04 '16 at 15:29

1 Answers1

0

What values are you getting for year, month and day? If they are numbers (or numeric strings like "2016", "3", "10"), you can create a Date, then compare it to the current date by creating a date for today and zero the hours, e.g.

var d0= new Date(year, month-1, day);

// Ensure d0 is a valid date
if (!d0 || d0.getMonth() != month-1) {
  // d0 was not a valid date
} 

var d1 = new Date();
d1.setHours(0,0,0,0);

if (d0 > d1) {
  //d0 is a future date;
}
RobG
  • 142,382
  • 31
  • 172
  • 209