2

I have a form through which I want to accept date only within give date range. But, which ever date I am fetching, it is returning false and showing incorrect range. Following are the codes related-

register.html-

<div class="form-group row">
      <label for="date" class="col-sm-2 col-form-label class='control-label' ">Date of Birth</label>
      <div class="col-sm-5">
      <input type="date" max="2010-12-31" min="1990-01-01"  id="dob" placeholder="Date of birth"> 
      </div>
    </div>

controller.js-

var dobInput = document.forms["myform"]["dob"].value;
    var maxdate = new Date("2010-12-31");
    var mindate= new Date("1990-01-01");
    if(maxdate>dobInput && dobInput>mindate)
    {
        alert("correct range");
    }
    else{
        alert("Input out of range");
return false;
    }
maria.m
  • 110
  • 7

2 Answers2

1

The Value you're getting is returned as a string, however you're attempting to evaluate this against Date type variables - this will not work as a string to string evaluation will be done lexicographically.

You should instead convert the value to a date first:

var inputDate = new Date(dobInput);
if(maxdate>inputDate && inputDate >mindate){
   ...
Community
  • 1
  • 1
Kallum Tanton
  • 802
  • 7
  • 22
0

Your input is a string. so convert to Date first and check with getTime method. Correct code is as below..

var dobInput = document.forms["myform"]["dob"].value;
var maxdate = new Date("2010-12-31");
var mindate= new Date("1990-01-01");
var dateToChk = new Date(dobInput);
if(maxdate.getTime()>dobInput.getTime() && dobInput.getTime()>mindate.getTime())
{
    alert("correct range");
}
else{
    alert("Input out of range");
    return false;
}
Thanga
  • 7,811
  • 3
  • 19
  • 38