Last updated on November 26th, 2024 at 12:50 pm

This JavaScript code restricts certain character inputs using JavaScript’s onKeypress event.

Using the OnKeypress event, you can trap and prevent certain characters (represented by ASCII decimal codes) from being entered in a form field. Just look up the ASCII code for any other characters you wish to block and add it to the script.

Prevent all special characters (like !@#$%^&* etc) in textarea

<textarea rows=2 cols=20 name=comments onKeypress="if ((event.keyCode > 32 && event.keyCode < 48) || (event.keyCode > 57 && event.keyCode < 65) || (event.keyCode > 90 && event.keyCode < 97)) event.returnValue = false;"></textarea>

Using this event, input field will not accept double or single quotes

<input type=text name=txtEmail onKeypress="if (event.keyCode==34 || event.keyCode==39) event.returnValue = false;"/>

This input field only accept numbers

<input type=text name=txtPostalCode onKeypress="if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;">

Another example using function,

<textarea rows="2" cols="20" name="comments"
    onkeypress="validateKey(event)">
</textarea>

<script>
    function validateKey(event) {
        const key = event.key;
        const isSpecialChar =
            (key >= ' ' && key <= '/') || // Special characters before '0'
            (key >= ':' && key <= '@') || // Special characters between '9' and 'A'
            (key >= '[' && key <= '`') || // Special characters between 'Z' and 'a'
            (key >= '{'); // Special characters after 'z'

        if (isSpecialChar) {
            event.preventDefault(); // Block the keypress
        }
    }
</script>

When a key is pressed, the validateKey function checks if the character is a special character by comparing its ASCII value ranges.If it’s a special character, event.preventDefault() stops the input.

Demo