Monday, November 25, 2013

Block Special Characters in JavaScript.

Copy and paste in <Head> section.

<script language="javascript" type="text/javascript">
        function DisableSplChars(e) {
            var keynum
            var keychar
            var numcheck
            // For Internet Explorer
            if (window.event) {
                keynum = e.keyCode
            }
            // For Netscape/Firefox/Opera
            else if (e.which) {
                keynum = e.which
            }
            keychar = String.fromCharCode(keynum)
            //List of special characters you want to restrict
            if (keychar == "!" || keychar == "@" || keychar == "#"
    || keychar == "$" || keychar == "%" || keychar == "^" || keychar == "&"
    || keychar == "*" || keychar == "(" || keychar == ")"
    || keychar == "<" || keychar == ">") {
                return false;
            }
            else {
                return true;
            }
        }


        function ValidateName(control, e) {
            if (control.value.length == 0 || !control.value.match(/[^\s]/)) {
                alert("Empty string detected.");
                control.focus();


                if (window.event) {
                    window.event.returnValue = false;
                }
                else {
                    e.preventDefault();
                }
            }
        }
    </script>

and, add in TextBox onkeypress="javascript:return DisableSplChars(event);"

<asp:TextBox ID="TextBox1" runat="server" onkeypress="javascript:return DisableSplChars(event);"></asp:TextBox>

No comments:

Post a Comment