
validate is a small JavaScript plugin that validates the date input and returns true/false if the value is a valid dd/mm/yyyy string.
How It Works:
- Check the pattern is correct using Regex. By default, the plugin accepts 0-31/01-12/YYYY date format.
- Deal with the number of days in each month with an object that’s keyed to the month number.
- If the month supplied doesn’t correspond to a key in months obj then it’s invalid.
- Check if is it a leap year? if so amend Feb to 29 days.
- If date[0] is > 0 and =< the days in the month it’s valid, else invalid.
How to use it:
1. Import the validate component into the document.
import validateDate from './validateDate.js';
2. Insert a date input into your web form and create a container to hold the result.
<form id="mainform" action="#" method="POST" class="form" autocomplete="off">
<input type="hidden" autocomplete="false">
<label class="form__label" for="dateinput">Date (DD/MM/YYYY):</label>
<input class="form__input" id="dateinput" name="date" type="text" minlength="10" maxlength="10" pattern="^([0-2][0-9]|(3)[0-1])([\/])(((0)[0-9])|((1)[0-2]))([\/])([0-9]{4})$" placeholder="DD/MM/YYYY" value="" required>
<input class="form__submit" type="submit" name="submit" value="Validate">
<p class="form__result"> </p>
</form>3. The example App.js to validate the date input and print the result in the page.
let form = document.querySelector('#mainform');
form.addEventListener("submit", function(e) {
e.preventDefault();
let date = document.querySelector('#dateinput').value;
let output = date + ' is <strong>' + (validateDate(date) ? 'valid' : 'invalid') + '</strong>.'
document.querySelector('.form__result').innerHTML = output;
});Override the default Regex used to validate the date input.
let regex = RegExp("^([0-2][0-9]|(3)[0-1])([\/])(((0)[0-9])|((1)[0-2]))([\/])([0-9]{4})$");
if(!regex.test(input)) {
return false;
}






