Help with a function that validates Letters - JavaScript

0

Hello, I have the following code that I got (It's in JavaScript) which validates the entry of only characters; and not special numbers or characters; within a input :

Code:

function SoloLetras(e)
{
   key = e.keyCode || e.which;
   tecla = String.fromCharCode(key);
   letras = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZáéíóúabcdefghijklmnñopqrstuvwxyz";
   especiales = "8-37-39-46";

   tecla_especial = false;

   for(var i in especiales){
        if(key == especiales[i]){
            tecla_especial = true;
            break;
        }
    }

    if(letras.indexOf(tecla)==-1 && !tecla_especial){
        return false;
    }

}

What I want to do is, in addition to everything, allow me to enter blank spaces at the time of writing. That if you could help me, I would be very grateful.

PD. The code works for me, but I want to add the aforementioned.

    
asked by 27.12.2017 в 03:02
source

2 answers

1

especiales has to be an array so that you can scroll through it as you intend within the loop for . You just have to add the 32 that is the code of the space.

especiales = [8, 32, 37, 39, 46];

Key codes .

    
answered by 27.12.2017 / 03:27
source
0

You add a listener to the text, and with a regex check if each letter entered at the time it is written meets the regular expression, if I do not use the preventDefault () method so that I can not write and false return.

function _keyValidation() {
 var text = document.getElementById("area");
 text.addEventListener("keypress", _check);
  function _check(e) {
  var textV = "which" in e ? e.which : e.keyCode,
      char = String.fromCharCode(textV),
      regex = /[a-z]/ig;
      if(!regex.test(char)) e.preventDefault(); return false;
  }
}

window.addEventListener("load", _keyValidation);
<textarea id="area" cols=40 rows=7>

</textarea>
    
answered by 27.12.2017 в 04:43