Disabling some special characters in text area

2019-05-30 23:27发布

Hey guys, I'm thinking of ways to disable users from typing some special characters like < and >. But I would like them to use full stops and commas and question marks and exclamation marks and quotes. I've come up with this piece of code but it doesn't seem to allow any special character.:

<script type="text/JavaScript">
function valid(f) {
!(/^[A-zÑñ0-9]*$/i).test(f.value)?f.value = f.value.replace(/[^A-zÑñ0-9]/ig,''):null;
} 
</script>

3条回答
你好瞎i
2楼-- · 2019-05-30 23:45

Try with this...

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;
    }
  }
查看更多
放我归山
3楼-- · 2019-05-30 23:53

There are several ways of doing this, none of them are a good way to go tho, but we'll get to that.

  1. you can bind to onkeyup/onkeydown/onkeypress events on the element and cancel events for characters you have blacklisted. This will not stop people from pasting the characters into the field however.

  2. You can bind to the onchange event of the element and them remove the blacklisted characters from it, once the user is done inputting.

The problem with any type of sanitizing like this in javascript is that it is trivial for a user with a tiny bit of knowhow, to circumvent these measures and still upload the offending characters to the server anyway.

So if you don't want to allow special characters in the user generated input you should either

  1. remove them serverside after the userinput has been submitted
  2. keep them but encode them into html entities &gt; and &lt; for > and < for instance before outputting them anywhere on your webpage.
查看更多
爷的心禁止访问
4楼-- · 2019-05-31 00:10

why not simply check the character pressed on "onKeyDown" event?

<textarea id="foo"></textarea>

<script>
 document.getElementById('foo').onkeydown = validate;

 function validate(){
   var evtobj = window.event? event : e; // IE event or normal event
   var unicode = evtobj.charCode? evtobj.charCode : evtobj.keyCode;
   var actualkey = String.fromCharCode(unicode);
 ]

 return (/^[A-zÑñ0-9]*$/i).test(actualKey);
</script>

This simply gets the key which was pressed, and if it is a valid one returns true, otherwise false, this, in term, determines if the key is actually written in the textarea or not

查看更多
登录 后发表回答