Disabling some special characters in text area

时间秒杀一切 提交于 2019-12-08 05:40:12

问题


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>

回答1:


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.



回答2:


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:


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



来源:https://stackoverflow.com/questions/4991259/disabling-some-special-characters-in-text-area

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!