How to correctly validate an input onkeypress using javascript?

1

I've been practicing with events in javascript, because I'm tired of placing onclick, onfocus or other event as an attribute in HTML tags and I wanted to share this code, can it improve in terms of security or can it be shorter?

divKeys=document.querySelector('.keys');
divRegex=document.querySelector('.regex');
document.querySelector('.input').onkeypress = function(e) {
  //console.log(e);
  let keyCodes = RegExp('^(0|[8-9]|13|1[5-7]|28|3[7-9]|40|46|4[9]|5[0-9]|6[5-9]|[7-8][0-9]|90|9[6-9]|10[0-9]|11[0-9]|12[0-3])$');
  let regex = /[0-9]/;
  let tecla = e.keyCode;
  let tecla_final = e.key;
  let cond1 = keyCodes.test(tecla);
  let cond2 = regex.test(tecla_final);
  divKeys.innerText='KeyCodes: '+(cond1==true?'true':'false');
  divRegex.innerText='RegExp: '+(cond2==true?'true':'false');
  return cond1 && cond2 ? true : false;
}
<input type="text" class="input">
<br>
<h3>resultado</h3>
<label class='keys'>KeyCodes:</label>

<br>
<label class='regex'>RegExp:</label>
    
asked by Angel Zambrano 25.05.2018 в 02:52
source

0 answers