How to disallow specific characters when entered in a form input in plain JavaScript?

16,259

Solution 1

I have updated your initial fiddle here.

The method I chose for simplicity was to get the string character of the key attempting to be pressed and then checked if it were in the prohibited array.

You should note that I changed to using the onkeypress instead of onkeydown event, as the first includes modifiers like the shift key when utilising fromCharCode(), while the other does not (as keypressed checks the full key combination).

Code:

el.onkeypress = function(e) {   
    // invalid character list
    var prohibited = "!@#$%^&*()+=;:`~\|'?/.><, \"";
    // get the actual character string value
    var key = String.fromCharCode(e.which);
    // check if the key pressed is prohibited    
    if(prohibited.indexOf(key) >= 0){
        console.log('invalid key pressed');    
        return false;
    }
    return true;    
};

Solution 2

prohibitedChars is a string of unwanted characters.So you can split the input value and then use indexOf method to validate with prohibitedChars

// String of prohibited chars
var prohibitedChars = "!@#$%^&*()+=;:`~\|'?/.><, \"";
var _input = document.getElementById("username");
//Validate on keyup
_input.addEventListener('keyup',function(){
var _getIpValue = _input.value;

_validateField(_getIpValue);
})
//This function does the actual validation
function _validateField(ipVal){
// split the input 
var arrayString = ipVal.split("");
//iterate through each of them and check if it match with any chars of prohibitedChars
arrayString.forEach(function(item){
 // if item match it will retun -1
 if(prohibitedChars.indexOf(item) !== -1){
  alert(item +" Not allowed");
  _input.value = ""
 }
})
}

Check this JsFiddle

Share:
16,259
Angel Politis
Author by

Angel Politis

Author • Entrepreneur • Developer • 25 Skills: • Expert in: html, css, javascript, php, sql • Pretty good at: java, c++, python Let's talk: • I've just recently decided to give Twitter a chance. • For professional inquiries, you can contact me at [email protected]. 🎇 THE END 🎇

Updated on June 17, 2022

Comments

  • Angel Politis
    Angel Politis almost 2 years

    I am trying to create a username textbox that blocks the user's input if it is any of these (!,@,#,$,%,^,&,*,(,),+,=,;,:,`,~,|,',?,/,.,>,<,,, ,").

    The idea is not to make the check afterwards but at the moment of the click. I've had two ideas of doing that both ending up bad. The first JS script doesn't seem to work at all and the second JS script freezes the entire tab.

    My current HTML code is:

    <form name = "RegForm" class="login">
       <input type="text" name="username" id="username" placeholder="Enter your username">
    </form>
    

    My first JS script is: https://jsfiddle.net/ck7f9t6x

    userID_textfield.onkeydown = function(e) {   
        var prohibited = "!@#$%^&*()+=;:`~\|'?/.><, \"";
        var prohibitedchars = prohibited.split("");
        var prohibitedcharcodes = new Array();
    
        for (var i = 0; i < prohibitedchars.length + 1; i++) {
            prohibitedcharcodes.push(prohibitedchars[i].charCodeAt(i));
            for (var a = 0; a < prohibitedcharcodes.length + 1; a++) {
                if (prohibitedcharcodes[a] === e.which) {
                    return false;
                }
                else {
                    return true;
                }
            }
        }
    }
    

    My second JS script is: https://jsfiddle.net/2tsehcpm/

    var username_textfield = document.forms.RegForm.username;
    username_textfield.onkeydown = function(e) {
        var prohibited = "!@#$%^&*()+=;:`~\|'?/.><, \"";
        var prohibitedchars = prohibited.split("");
        var text = this.value.toString();
        var chars = text.split("");
        for (var i = 0; i < chars.length + 1; i++) {
            for (var a = 0; a < prohibitedchars.length + 1; a++) {
                if (chars[i] == prohibitedchars[a]) {
                    chars[i] = null;
                }
            }
        }
        this.value = chars.join();
    }
    

    What is wrong with my code and what should I be doing instead?

    Any enlightening answer would be greatly appreciated!