Javascript : How to validate the YYYY or MM/YYYY or DD/MM/YYYY in single text box

I will use a single text box to capture user input. Allowed format YYYY or MM/YYYY or DD/MM/YYYY. How can i validate it ?


    <input type="text" class="form-control" id="editDOB" name="editDOB"  onkeypress="return isNumberKeys(event)" onpaste="return false" maxlength="10">


    function isNumberKeys(evt) {
                var charCode = (evt.which) ? evt.which : event.keyCode
                if (charCode > 31 && (charCode > 57))
                    return false;
                return true;

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: