0

How to validate html <input type='date'/> is greater than today?

The following is my code:

<div class="form-group">
<label class="col-sm-2" for='id_dateOfBirth'>Birth Date </label>
<div class="col-sm-10">
    <input class='form-control' name="dateOfBirth" id='id_dateOfBirth' type='date'>
</div>

I want to check whether date is greater than today using JavaScript.

rahul.m
  • 5,572
  • 3
  • 23
  • 50

2 Answers2

13

What I understand from your question is - "Before posting the form, you'd like to check if the DOB field has a date that must not be greater than today's date.". If this is correct, then try this, Hope this help -

<script type="text/javascript">
    function checkDOB() {
        var dateString = document.getElementById('id_dateOfBirth').value;
        var myDate = new Date(dateString);
        var today = new Date();
        if ( myDate > today ) { 
            $('#id_dateOfBirth').after('<p>You cannot enter a date in the future!.</p>');
            return false;
        }
        return true;
    }
</script>
Nitesh Goyal
  • 586
  • 5
  • 11
1

If you can use php do: <input type="date" name="date1" max=<?php echo date('Y-m-d'); >

if only js:

document.getElementById("id_dateOfBirth").setAttribute("max", today);

where today is eg 2017-03-10 to get this date use eg :

      new Date().toJSON().split('T')[0] 
MaoStream
  • 188
  • 9