我想验证用户输入的文本为字母数字和空格
允许 -> a 到 z、A 到 Z、0 到 9 和空格
我想使用Javascript验证它
平台 ASP.Net 2.0、C#
到目前为止我尝试过...
<script type="text/javascript">
function IsValidCharNum(event) {
var KeyBoardCode = (event.which) ? event.which : event.keyCode;
if ((KeyBoardCode < 96 || KeyBoardCode > 123) && (KeyBoardCode < 65 || KeyBoardCode > 90) && (KeyBoardCode < 48 || KeyBoardCode > 57) && (KeyBoardCode < 32 || KeyBoardCode > 32)) {
return false;
}
return true;
} </script>
onkeypress="return IsValidCharNum(event)" 的文本框(没有网格视图和更新面板)它正在工作
像这样使用RegularExpression Validator
:
<asp:TextBox ID="txtName" runat="server" ></asp:TextBox>
<asp:RegularExpressionValidator ID="REValphaOnly" runat="server" ErrorMessage="Please enter only alphanumeric." ControlToValidate="txtName" ValidationExpression="^[a-zA-Z0-9 ]+$"></asp:RegularExpressionValidator>
更多信息 :
http://msdn.microsoft.com/en-us/library/ms972966.aspx
http://www.codeproject.com/Tips/472728/RegularExpressionValidator-In-ASP-NET
你可以通过在文本框的keyup上调用javascript来做到这一点。
<script type="text/javascript">
function ValidateText(i) {
if (/[^0-9a-bA-Bs]/gi.test(fieldname.value)) {
alert("Only alphanumeric characters and spaces are valid in this field");
fieldname.value = "";
fieldname.focus();
return false;
}
}
</script>
<asp:TemplateField >
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" onkeyup ="ValidateText(this);"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
最后创建了一个正确的函数来完成验证
页面.aspx
<script type="text/javascript">
function IsValidCharNum(event) {
var KeyBoardCode = (event.which) ? event.which : event.keyCode;
if ((KeyBoardCode < 96 || KeyBoardCode > 123) && (KeyBoardCode < 65 || KeyBoardCode > 90) && (KeyBoardCode < 48 || KeyBoardCode > 57) && (KeyBoardCode < 32 || KeyBoardCode > 32)) {
return false;
}
return true;
}
<asp:TextBox ID="TextBox1" runat="server" onkeypress="return IsValidCharNum(event)"></asp:TextBox>
同时使用 GridView 和 UpdatePanel