Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Javascript functiion not working as expected

Currently I'm trying create a script that will only allow A-Za-z, 0-9, white space and comma. Here is my script:

<textarea name="commentText" onkeypress="return filterCharAll(event,this);"></textarea>
function filterCharAll(e, t) {
 if (window.event) {
 var charCode = window.event.keyCode;
 }
 else if (e) {
 var charCode = e.which;
 }
 else { return true; }
 if ((charCode > 47 && charCode < 58) || (charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || (charCode == 188 || charCode == 32 || charCode == 13)) {
 return true;
 } else {
 return false;
 } 
}

Everything is working perfectly! But the comma is not working. When I press it, nothing happens

JSfiddle: https://jsfiddle.net/mek7qy8h/

Can you help me? Thank you.

Answer*

Draft saved
Draft discarded
Cancel
6
  • You shouldn't use .key since it will return the name of a special key, e.g. "Alt" which will match the regular expression without ^$ anchors. Commented Dec 12, 2018 at 1:25
  • Do you know how to avoid CTRL+V? Is possible insert certain characters using CTRL+V inside textarea Commented Dec 12, 2018 at 1:30
  • @inukix You can just return false on a paste event Commented Dec 12, 2018 at 1:33
  • But it will block paste on every box on my page? I need only inside this specfic textarea. Commented Dec 12, 2018 at 1:34
  • @inukix See the code in the answer - just like you can onkeypress="return filterCharAll(event);" for just that element, you can similarly onpaste="return false;" for just that element (paste would only be disabled on outer elements as well if the handler was attached to some outer element) Commented Dec 12, 2018 at 1:36

lang-js

AltStyle によって変換されたページ (->オリジナル) /