Prevent (Restrict) entering specific characters in TextBox using JavaScript

nedash
 
on Jun 29, 2021 10:57 PM
Sample_393057.zip
810 Views

hi

I have a textbox on page

I want users can't enter special characters into textbox like this letter:

()*&^%$#@!<>/\

how I can do it?

Best regards

Neda

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jul 01, 2021 03:27 AM
on Jul 01, 2021 03:31 AM

Hi nedash,

Refer below code.

HTML

<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <input type="text" id="text1" onkeypress="return IsSpecialKeys(event);" ondrop="return false;" onpaste="return false;" />
    <span id="error" style="color: Red; display: none">()*&^%$#@!<>/\ Characters are not allowed.</span>
    <script type="text/javascript">
        function IsSpecialKeys(e) {
            var specialKeys = new Array();
            specialKeys.push(')');
            specialKeys.push('(');
            specialKeys.push('*');
            specialKeys.push('&');
            specialKeys.push('^');
            specialKeys.push('%');
            specialKeys.push('$');
            specialKeys.push('#');
            specialKeys.push('@');
            specialKeys.push('!');
            specialKeys.push('<');
            specialKeys.push('>');
            specialKeys.push('/');
            specialKeys.push('\\');
            document.getElementById("error").style.display = "none";
            if (specialKeys.indexOf(e.key) != -1) {
                document.getElementById("error").style.display = "inline";
                return false;
            }
            return true;
        }
    </script>
</body>
</html>

Demo