Javascript validation: Block special characters

后端 未结 7 1974
广开言路
广开言路 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: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;
        }
    }
    

提交回复
热议问题