利用正则表达式避免输入空格通过客户端非空验证.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function checkForm() {
var txt1 = document.getElementById("TextBox1").value;
if (txt1==null||txt1 == "") {
alert('用户名不能为空!');
return false;
}
if (txt1.length < 6 || txt1.length > 10) {
alert('用户名必须6-10个字符');
return false;
}
// \s 匹配任何空白字符,包括空格、制表符、换页符等等。等价于 [ \f\n\r\t\v]。
//输入\s+ 代表匹配1-n个空格,只要用户名中有一个或多个空格都无法通过验证.
var regular = /\s+/g
if (regular.test(txt1)) {
alert('不能输入一串的空格!');
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><asp:Button ID="Button1"
runat="server" Text="Button"
onclick="Button1_Click" OnClientClick="return checkForm()" />
</div>
</form>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function checkForm() {
var txt1 = document.getElementById("TextBox1").value;
if (txt1==null||txt1 == "") {
alert('用户名不能为空!');
return false;
}
if (txt1.length < 6 || txt1.length > 10) {
alert('用户名必须6-10个字符');
return false;
}
// \s 匹配任何空白字符,包括空格、制表符、换页符等等。等价于 [ \f\n\r\t\v]。
//输入\s+ 代表匹配1-n个空格,只要用户名中有一个或多个空格都无法通过验证.
var regular = /\s+/g
if (regular.test(txt1)) {
alert('不能输入一串的空格!');
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><asp:Button ID="Button1"
runat="server" Text="Button"
onclick="Button1_Click" OnClientClick="return checkForm()" />
</div>
</form>
</body>
</html>