4

There are two input fields of type text to write a start date and end date in format mm/dd/yyy. I need a JavaScript function to check that the date range interval between those entered dates does not exceed 14 days. And the maximum date should be the current date. Is there a plugin or a fast solution for this? I tried to use the jQuery UI datepicker which would work fine, but I have a custom GetElementByClassName function which conflicts with jQuery.

Thank you.

1
  • Why don't you automatically display date in the second text box adding +14 so that there is no necessity to check Commented Apr 22, 2011 at 12:25

2 Answers 2

2

The following snippets should give you some ideas.

<script>
    var date1 = '01/14/2011';
    var date2 = '01/25/2011';

    // calculate the number of days between date1 and date2
    var daysBetween = new Date(date2).getTime() - new Date(date1).getTime();
    alert('days between = ' + daysBetween / 86400000);

    // check date3 against current date
    var now = new Date();
    var date3 = new Date('04/20/2011');
    if (date3 < now)
      alert('date3 is less than current date');

</script>

So to combine into a function, you could do something like this:

<script>
    function checkDates(date1, date2) {
        // calculate the number of days between date1 and date2
        var daysBetween = (new Date(date2).getTime() - new Date(date1).getTime()) / 86400000;

        if (daysBetween > 14)
          return false;

        var now = new Date();
        if (date2 < now)
          return false;

        return true;

    }
Sign up to request clarification or add additional context in comments.

Comments

0

I worked on this problem and I found focusout function to be the best solution that match my requirement. Jquery code:

$("#datefield").focusout(function () {
  date = $("#datefield").val();
  if (date > "2021-06-30" || date < "2020-07-01") {
    alert("Please enter a valid date.");
    $("#datefield").val("");
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.