0

I have made a function that is called on every key press that restricts the special characters Here is HTML snippet

<input maxlength="20" type="text" id="txtFirstName" name="txtFirstName" onkeypress="validateUserInput(event)">

and function

var validationCode = [33, 34, 35, 36, 37, 38, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 91, 92, 93, 94, 95, 123, 124, 125, 126];
// [!,",#,$,%,&,(,),*,+,,-,.,/,0,1,2,3,4,5,6,7,8,9,:,;,<,=,>,?,@,[,\,},^,_,{,|,},~,]

function validateUserInput(event) {
    if (validationCode.indexOf(event.charCode) != -1) {
        event.preventDefault();
    }
}

I want the user to restrict all the special character but he can enter characters of other languages (Chinese/Japanese).

Above function works for the entered ASCII characters but fails when user copy paste into the field.

Is there any other best and efficient way to do so?

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189

0 Answers0