How to validate special characters in a text field

5

The problem I have is that I need to validate a text field so that it only accepts ";" and "_" . So far it does not work for me with the code I have.

Code:

 function doNotSubmitFormOnEnterPress(event) {
    if (event.keyCode === 188 ) {
           return false;
    }
    return true;
 }
    
asked by Critical Ghost 19.05.2017 в 17:36
source

2 answers

5

You can do this with Jquery , You can validate if the Shift key is pressed, with the property shiftKey , will return a value boolean if the key is pressed or not

$('#valor').keydown(function(e) {
   if(e.shiftKey && e.keyCode ===188|| e.shiftKey && e.keyCode ===189)
     return true;
   if (e.key.length == 1) 
        return false
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"  id="valor" >
    
answered by 19.05.2017 / 17:55
source
1

I suggest using keypress instead of keyDown so it does not limit the activation of the ctrl keys, such as: Backspace , Delete , Etc. Although I lean towards the use of jQuery as well, I show in its place and for illustrative purposes the use of addEventListener () to handle the onKeyPress event associated with <input> , as well as the use of event.preventDefault () , to prevent the normal flow of <input> in case of not typing the required values.

Example:

document.getElementById("name").addEventListener("keypress", doNotSubmitFormOnEnterPress);

function doNotSubmitFormOnEnterPress(event) {
 if(";_".indexOf(event.key) == -1){ // colocar la cadena de caracteres permitidos
  event.preventDefault();
 };
};
<input id="name">
    
answered by 19.05.2017 в 19:09