Skip to content
Advertisement

JavaScript Onkeyup expiry date

How can i set onkeyup to output this format 00/00 instead 00/00/0000

<input type="text" onkeyup="
    var v = this.value;
    if (v.match(/^d{2}$/) !== null) {
        this.value = v + '/';
    } else if (v.match(/^d{2}/d{2}$/) !== null) {
        this.value = v + '/';
   }"> 

Advertisement

Answer

You could add maxlength="5"

<input type="text" maxlength="5" onkeyup="
    var v = this.value;
    this.value = v
      .replace(/^(d{2})(?:/?)(d{1,2})$/, `$1/$2`)
      .replace(/^(d{2})/$/, '$1');
   "> 

I also improved your regex to use replace and remove the / automatically

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement