Javascript validation: Block special characters

后端 未结 7 1936
广开言路
广开言路 2020-12-09 05:50

How can I restrict users from entering special characters in the text box. I want only numbers and alphabets to be entered ( Typed / Pasted ).

Any samples?

相关标签:
7条回答
  • 2020-12-09 06:41

    I think checking keypress events is not completely adequate, as I believe users can copy/paste into input boxes without triggering a keypress.

    So onblur is probably somewhat more reliable (but is less immediate).

    To truly make sure characters you don't want are not entered into input boxes (or textareas, etc.), I think you will need to

    1. check keypress (if you want to give immediate feedback) and
    2. also check onblur,
    3. as well as validating inputs on the server (which is the only real way to make sure nothing unwanted gets into your data).

    The code samples in the other answers will work fine for doing the client-side checks (just don't rely only on checking keypress events), but as was pointed out in the accepted answer, a server-side check is really required.

    0 讨论(0)
  • 2020-12-09 06:41

    A few of the options are deprecated as of today. So watch out for those.

    If you try <input onkeypress="blockSpecialCharacters(event)" />, an IDE like WebStorm will slash out event and tell you:

    Deprecated symbol used, consults docs for better alternative

    Then when you get to the JavaScript, console.log(e.keyCode) will also give keyCode and say:

    Deprecated symbol used, consults docs for better alternative

    Anyways I did it using jQuery.

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>
    
    <input id="theInput" />
    
    <script>
        function blockSpecialCharacters(e) {
                let key = e.key;
                let keyCharCode = key.charCodeAt(0);
    
                // 0-9
                if(keyCharCode >= 48 && keyCharCode <= 57) {
                    return key;
                }
                // A-Z
                if(keyCharCode >= 65 && keyCharCode <= 90) {
                    return key;
                }
                // a-z
                if(keyCharCode >= 97 && keyCharCode <= 122) {
                    return key;
                }
    
                return false;
        }
    
        $('#theInput').keypress(function(e) {
            blockSpecialCharacters(e);
        });
    </script>
    
    0 讨论(0)
  • 2020-12-09 06:45

    For special characters:

    var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
    
    for (var i = 0; i < document.formname.fieldname.value.length; i++) {
        if (iChars.indexOf(document.formname.fieldname.value.charAt(i)) != -1) {
            alert ("Your username has special characters. \nThese are not allowed.\n Please remove them and try again.");
            return false;
        }
    }
    
    0 讨论(0)
  • 2020-12-09 06:45

    Basically, just use an appropriate onkeypress handler. See http://www.qodo.co.uk/blog/javascript-restrict-keyboard-character-input/ and the example http://www.qodo.co.uk/wp-content/uploads/2008/05/javascript-restrict-keyboard-character-input.html

    0 讨论(0)
  • 2020-12-09 06:46

    You have two approaches to this:

    1. check the "keypress" event. If the user presses a special character key, stop him right there
    2. check the "onblur" event: when the input element loses focus, validate its contents. If the value is invalid, display a discreet warning beside that input box.

    I would suggest the second method because its less irritating. Remember to also check onpaste . If you use only keypress Then We Can Copy and paste special characters so use onpaste also to restrict Pasting special characters

    Additionally, I will also suggest that you reconsider if you really want to prevent users from entering special characters. Because many people have $, #, @ and * in their passwords.

    I presume that this might be in order to prevent SQL injection; if so: its better that you handle the checks server-side. Or better still, escape the values and store them in the database.

    0 讨论(0)
  • 2020-12-09 06:47

    It would help you... assume you have a form with "formname" form and a text box with "txt" name. then you can use following code to allow only aphanumeric values

    var checkString = document.formname.txt.value;
    if (checkString != "") {
        if ( /[^A-Za-z\d]/.test(checkString)) {
            alert("Please enter only letter and numeric characters");
            document.formname.txt.focus();
            return (false);
        }
    }
    
    0 讨论(0)
提交回复
热议问题