You cannot do this by rejecting keypresses, because the input has to go through invalid values in order to get to a valid one.
If for example the user wants to enter 01/01/2000, the input would be considered invalid as soon as they type the first zero. Also consider the user has to be able to type the slash after having entered 01, even though 01/
is not a valid date.
Better is not to reject any keys, also because you don't want the user to think their keyboard is broke. Instead apply styling to the input
box to indicate whether the input is (in)valid.
For your desired validation (YYYY
, MM/YYYY
or DD/MM/YYYY
) you could split the input by the slash, test that the number of parts is OK, and that when parsed by JavaScript as a Date (providing default values for day and month), it yields exactly the same date when converted back to string:
inp.addEventListener('input', function () {
var parts = this.value.split('/'),
fmt = ['01','01',...parts].slice(-3).reverse().join('-'),
json = (new Date(fmt).toJSON() || '').substr(0,10),
ok = parts.length < 4 && fmt === json;
this.style.border = ok ? '' : '2px solid red';
});
<input id="inp"> (YYYY or MM/YYYY or DD/MM/YYYY)
https://stackoverflow.com/questions/8647893/regular-expression-leap-years-and-more
https://stackoverflow.com/questions/6402743/regular-expression-for-mm-dd-yyyy-in-javascript – marvel308 Aug 05 '17 at 07:23