Javascript Form How to - Do date range validation








Question

We would like to know how to do date range validation.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!-- w  ww. ja  v  a2  s  . c  om-->
function validation(form) {
    var v2 = document.getElementById('v2');
    var date = new Date(v2.value);
    document.writeln(v2.value, date);
    document.writeln('<br/>');
    if (date > new Date('1/12/2012') && date < new Date('1/1/2013')) {
        // date is in your valid range
        document.writeln ('good date!')
        return true;
    } else {
        // date is not in your valid range
        document.writeln("date is not in the range")
        return false;
    }
}
document.getElementById('myButton').onclick = validation

</script>
</head>
<body>
  <form id="myform">
    <input type='date' id='v2' name='v2' value=''>Time 
    <input type='time' name='v3' value=''>Place 
    <input type='text' name='v4' value=''>
    <input type="button" id="myButton" value="Enter" />
  </form>
</body>
</html>

The code above is rendered as follows: