-5

I need to be able to add a validation (alertbox) if the user selects a previous date from the calendar.

Today's date is 13/11/2015. If the user was to select 12/11/2015 it should display an alert box saying "Please enter a valid date."

I've looked online and can't seem to find anything to do with this.

Can this be done with javascript?

<input type="date" id="leaveDate">
<script>
     alert("Please enter a valid date.");
</script>
Imraanstack2
  • 1
  • 1
  • 4

2 Answers2

1

Considering you want a solution in javascript, here is something you can try with onchange function.

<input type='date' onchange="validateDate()" id='mydate'></input>

<script>
function validateDate() {
    var userdate = new Date(document.getElementById("mydate").value).toJSON().slice(0,10);
    var today = new Date().toJSON().slice(0,10);
    if(userdate < today){
      alert('Your message');
    }
}
</script>

PS: Replace 'Your message' with the text you want to display.

Karthik RP
  • 1,028
  • 16
  • 26
0

If you dont want the user to select the past dates then I would suggest you to disable it like this using the datepicker:

$("#mydate").datepicker({ minDate: 0 });

However if you are intended to do the alert message approach then the thread: Check if date is in the past Javascript is doing what you are looking for.

Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • Downvoter, please care to leave a comment! :) – Rahul Tripathi Nov 13 '15 at 13:45
  • it should display an alert box saying "Please enter a valid date." . not what OP asked :/ – Hacketo Nov 13 '15 at 13:47
  • @Hacketo:- I am aware of what OP has asked for. Infact thats why I answered by saying `If you dont want the user to select the past dates` since alert message is just to restrict user from entering the past dates. Using alert seems not very productive to me. – Rahul Tripathi Nov 13 '15 at 13:49
  • I also downvoted for educational purposes, sorry . – Hacketo Nov 13 '15 at 13:58