I'm trying to validate a date input box so that it only accepts the current or future dates. So far I've been struggling to find answers which definitively does this.
Here is the HTML for the input box, excluding the <form>
tags:
<p>
<label>Date:</label>
<br>
<input type="number" name="date" placeholder="DD/MM/YYYY" onchange="checkDate()">
</p>
<div id="datewarn"></div>
Here is JavaScript code that I'm using which validates whether the input is in the format DD/MM/YYYY and that the numbers entered in are valid calender numbers, but this still accepts past dates.
function checkDate() {
var valid = true;
var redate = /(0[1-9]|[12][0-9]|3[01])[\/](0[1-9]|1[012])[\/](19|20)\d\d/;
if (!redate.test(document.bookingsform.date.value)) {
document.bookingsform.date.style.border = "1px solid red";
document.getElementById("datewarn").innerHTML = "Enter a date in the format DD/MM/YYYY.";
document.bookingsform.date.title = "Please enter a date in the format DD/MM/YYYY.";
document.getElementById("datewarn").style.display = "block";
valid = false;
} else {
document.bookingsform.date.style.border = "1px inset #EBE9ED";
document.bookingsform.date.style.borderRadius = "2px";
document.getElementById("datewarn").style.display = "none";
}
}
The research that I have done suggests using the date.js library? Is this an inbuilt library or this something I have to get?
This can only be JavaScript, no jQuery.
EDIT: Sorry, forgot to add the RegEx variable.
This is a function to tell, if the date you are entering is future date or not.
JS Function and use example:
const isFutureDate = (idate) =>{
let today = new Date().getTime();
idate = idate.split("/");
idate = new Date(idate[2], idate[1] - 1, idate[0]).getTime();
return (today - idate) < 0;
}
// Demo example
console.log(isFutureDate("02/03/3014")); // true
console.log(isFutureDate("01/01/2014")); // false
Here is implementation for you:
function checkDate(){
var idate = document.getElementById("date"),
resultDiv = document.getElementById("datewarn"),
dateReg = /(0[1-9]|[12][0-9]|3[01])[\/](0[1-9]|1[012])[\/]201[4-9]|20[2-9][0-9]/;
if(!dateReg.test(idate.value)){
resultDiv.innerHTML = "Invalid date!";
resultDiv.style.color = "red";
return;
}
if(isFutureDate(idate.value)){
resultDiv.innerHTML = "Entered date is a future date";
resultDiv.style.color = "red";
} else {
resultDiv.innerHTML = "It's a valid date";
resultDiv.style.color = "green";
}
}
test it with this HTML:
<p>
<label>Date:</label>
<br />
<input type="text" name="date" id="date" placeholder="DD/MM/YYYY" onkeyup="checkDate()" />
</p>
<div id="datewarn"></div>