-3

I know there are a few questions out there on this topic, but they all are either unclear or, they are using input[type="text"] in them.

In my HTML form I have an input of type date. So now I want to make sure that the date of birth is valid(Date is not in the future!). How do I do this?

YeetCoder
  • 304
  • 1
  • 3
  • 12
  • 3
    What have you tried so far? [You are expected to have made an attempt](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Taplar Jul 10 '19 at 19:24
  • 1
    Make a Date instance from it and compare that to `new Date()`. `>` and `<` comparisons work the way you'd expect for dates. – Pointy Jul 10 '19 at 19:24
  • 1
    So what is different with reading input text value and a date input value? – epascarello Jul 10 '19 at 19:26
  • There are many great libraries out there for working with dates, for example, https://momentjs.com/ - have you tried using something like this. – katamaster818 Jul 10 '19 at 19:29
  • Consider using the [`min` and `max` attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date#Additional_attributes). – showdev Jul 10 '19 at 19:32
  • 1
    There's a whole section on [validation](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date#Validation) in MDN's documentation of `input type="date"`... – Heretic Monkey Jul 10 '19 at 19:40

1 Answers1

0

The comments have suggested a number of approaches, but for the specific functionality you're implementing, most of them are overkill. This only requires a simple comparison operation.

document.getElementById("check").addEventListener("click", function(e){
  // Create a date variable which stores the current day at 00:00 local time.
  let today = new Date();
  today.setHours(0,0,0,0);

  // Parse the provided date in the default YYYY-MM-DD format.
  let birthdate = new Date(document.getElementById("birthdate").value);

  // Check whether the provided date is equal to or less than the current date.
  if (birthdate <= today) {
   document.getElementsByTagName("span")[0].textContent = "Valid!";
  } else {
   document.getElementsByTagName("span")[0].textContent = "Invalid!";
  }
});
<input type="date" id="birthdate"/>
<button id="check">Check</button>
<span></span>
IronFlare
  • 2,287
  • 2
  • 17
  • 27
  • StackOverflow is not a code request site. Answering questions that do not follow the community guidelines promotes more questions like this in the future. – Taplar Jul 10 '19 at 20:10