0

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 ?

HTML

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

Script

    function isNumberKeys(evt) {
                var charCode = (evt.which) ? evt.which : event.keyCode
                if (charCode > 31 && (charCode > 57))
                    return false;
                return true;
            }
Udayakumar
  • 145
  • 1
  • 1
  • 11
  • 1
    how about using `` – Gowtham Shiva Aug 05 '17 at 07:21
  • You will need to use RegEx if you want to use JS for this. What code have you got? What have you tried? Please give us a [Minimum, Complete and Verifiable Example](https://stackoverflow.com/help/mcve) so that we can help you with this. – Toastrackenigma Aug 05 '17 at 07:22
  • Use regex to validate it refer to the following
    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

1 Answers1

0

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)
trincot
  • 317,000
  • 35
  • 244
  • 286