JSFiddle - React, Tailwind, and code Playground
HTML
<form name="test">
<label>
<div> Your Birthday: </div>
<input type="text" name="birthday"><div style="display:none"> Invalid date </div>
</label>
</form>
JavaScript
function normalizeDate(dateString) {
if (dateString.length && dateString.length < 6) {
return '';
}
// If it's not at least 6 characters long (8/8/88), give up.
var date = new Date(dateString),
month, day;
// If input format was in UTC time, adjust it to local.
if (date.getHours() || date.getMinutes()) {
date.setMinutes(date.getTimezoneOffset());
}
month = date.getMonth() + 1;
day = date.getDate();
// Return empty string for invalid dates
if (!day) {
return '';
}
// Return the normalized string.
return date.getFullYear() + '-' +
(month > 9 ? '' : '0') + month + '-' +
(day > 9 ? '' : '0') + day;
}
// Test stuff
var form = document.forms['test'],
birthday = form.birthday,
validator = birthday.nextSibling;
// here's how you could use `normalizeDate`
birthday.onblur = function() {
var normalizedDate = normalizeDate(birthday.value);
if (normalizedDate) {
validator.style.display = 'none';
birthday.value = normalizedDate;
} else {
validator.style.display = 'block';
}
};
// just for this test, so you can hit enter to test it.
form.onsubmit = function() { birthday.onblur(); return false; }