Javascript 避免键入某些特殊字符

Javascript 避免键入某些特殊字符,javascript,character,Javascript,Character,我有一个用于证明用户名的文本框。但我想限制特殊字符在他们试图键入或粘贴单词(以及特殊字符)时的使用。我怎样才能通过js做到这一点。我已经写了一段代码,但是只有我能够在打字时限制那里的特殊字符,但是当我在文本框上粘贴一些单词时,无法限制这些字符。我的代码如下: <input type="text" name="bus_uname" id="bus_uname" class="reg-line-input" value="<?php echo ($back_uname!='')?$b

我有一个用于证明用户名的文本框。但我想限制特殊字符在他们试图键入或粘贴单词(以及特殊字符)时的使用。我怎样才能通过js做到这一点。我已经写了一段代码,但是只有我能够在打字时限制那里的特殊字符,但是当我在文本框上粘贴一些单词时,无法限制这些字符。我的代码如下:

<input type="text" name="bus_uname" id="bus_uname" class="reg-line-input"
  value="<?php echo ($back_uname!='')?$back_uname:'Business Username';?>"
  onblur="if(this.value=='') this.value='Business Username'"
  onFocus="if(this.value=='Business Username') this.value='';"
  onkeypress="return usernameonly(event, false)" />

这可能会对您有所帮助,也许替换整个单词中的字符是更好的解决方案;)
function usernameonly(e, decimal) {
    var key;
    var keychar;

    if (window.event) {
       key = window.event.keyCode;
    }
    else if (e) {
       key = e.which;
    }
    else {
       return true;
    }
    keychar = String.fromCharCode(key);

    if ((key==null) || (key==0) || (key==8) ||  (key==9) || (key==13) || (key==27) ) {
       return true;
    }
    else if ((("!@#$%^&*()_+-=?/.><,';:").indexOf(keychar) > -1)) {
       return false;
    }
    //else
    //   return false;
}
<input type="text" name="bus_uname" id="bus_uname" class="reg-line-input" value="<?php echo ($back_uname!='')?$back_uname:'Business Username';?>" onblur="if(this.value=='') this.value='Business Username'" onFocus="if(this.value=='Business Username') this.value='';" onkeypress="return usernameonly(event, false)" onpaste="return false" />