0

I have a simple validation date which doesn't seem to work. I wanted to ensure that the start date is not greater than the end date.

function validateDate() {
  var d1 = new Date.parse(document.getElementsByName("dt1").value);
  var d2 = new Date.parse(document.getElementsByName("dt2").value);

  if (d1.getTime() > d2.getTime())
    alert("Start date cannot be greater than End date");

}
<label for="dt1">Start Date : </label><input type="date" id="dt1">
<label for="dt2">End Date : </label><input type="date" id="dt2" onfocusout="validateDate()">

I attached a fiddle to demostrate this better : https://jsfiddle.net/63g99gk8/1/

I am a complete novice in doing javascript and would appreciate any advice and comments.

Kunj
  • 1,980
  • 2
  • 22
  • 34
Darren Soo
  • 15
  • 6
  • `Date.parse` is not a constructor so `new` is not valid. `getElementsByName` should be `getElementById`. – Alex K. Mar 08 '18 at 12:52
  • How are you making the input? – vityavv Mar 08 '18 at 12:52
  • Allways have a look in the console. There you'll find the error `Uncaught TypeError: Date.parse is not a constructor` – Jeff Mar 08 '18 at 12:55
  • 1
    What you need to know is an important thing in programming. How to debug. and then you will be saved. So you dont have to ask others to debug your code. – Mishel Parkour Mar 08 '18 at 12:56

2 Answers2

1

There are some mistakes in the code. You can directly create date object. And also use getElementById() to get values.

function validateDate(e) {

 var d1 = new Date(document.getElementById("dt1").value);
 var d2 = new Date(document.getElementById("dt2").value)

 if (d1.getTime() > d2.getTime())
  alert("Start date cannot be greater then End date");

}
<label for="dt1">Start Date : </label>
<input type="date" id="dt1">
<label for="dt2">End Date : </label>
<input type="date" id="dt2" onchange="validateDate(event);">
Ishwar Patil
  • 1,671
  • 3
  • 11
  • 19
0

You are using getElementsByName which returns a NodeList and not just the specific element. Seeing you have an id use getElementById instead.

Additionally new Date.parse is not valid. Use new Date() instead passing the value of your calendar to it as a parameter new Date(value).

See Documentation on Date for a more details.

var validateDate = function() {
 var d1 = new Date(document.getElementById("dt1").value);
 var d2 = new Date(document.getElementById("dt2").value);
  
 if (d1.getTime() > d2.getTime())
  alert("Start date cannot be greater then End date");

}
<label for="dt1">Start Date : </label><input type="date" id="dt1">
<label for="dt2">End Date : </label><input type="date" id="dt2" onfocusout="validateDate()">
Nope
  • 22,147
  • 7
  • 47
  • 72