本文介绍了我可以选择文本框中不允许的某些特殊字符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不想只允许像<这样的特殊字符。 >和&
我尝试过:
这里是我在互联网上搜索的代码,但此代码不接受所有特殊字符。
I don't want to allowed only the special character like < > and &
What I have tried:
and here's the code that i search on the internet but this code did not accept all of the special character.
<pre><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
body
{
font-size: 9pt;
font-family: Arial;
}
</style>
</head>
<body>
Alphanumeric value:
<input type="text" id="text1" onkeypress="return IsAlphaNumeric(event);" ondrop="return false;"
/>
<span id="error" style="color: Red; display: none">* Special Characters not allowed</span>
<script type="text/javascript">
var specialKeys = new Array();
specialKeys.push(8); //Backspace
specialKeys.push(9); //Tab
specialKeys.push(46); //Delete
specialKeys.push(36); //Home
specialKeys.push(35); //End
specialKeys.push(37); //Left
specialKeys.push(39); //Right
function IsAlphaNumeric(e) {
var keyCode = e.keyCode == 1 ? e.charCode : e.keyCode;
var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
document.getElementById("error").style.display = ret ? "none" : "inline";
return ret;
}
</script>
</body>
</html>
推荐答案
function IsAlphaNumeric(e) {
var keyCode = e.keyCode == 1 ? e.charCode : e.keyCode;
var ret = ((keyCode > 31 && keyCode < 127) && keyCode != 38 && keyCode != 60 && keyCode != 62);
document.getElementById("error").style.display = ret ? "none" : "inline";
return ret;
}
它允许使用的任何字符[]从32到126除了<和>和&
你可以轻松添加或排除他人。
另外,只需添加:do不依赖JavaScript(客户端)验证用户输入。您必须始终在服务器上的代码(VB,C#,等等)中运行相同的检查。
It will allow any character with ASCII code[^] from 32 to 126 apart from < and > and &
YOu can easily add or exclude others.
Also, just to add: do not rely on JavaScript (client side) validation for user input. You must always run the same checks in code (VB, C#, whatever) on the server as well.
这篇关于我可以选择文本框中不允许的某些特殊字符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!