我的页面是这样的:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
.ErrorControl
{
background-color: #FBE3E4;
border: solid 1px Red;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="TextBox1"
runat="server" ErrorMessage="Required"></asp:RequiredFieldValidator>
<br />
<br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ValidationExpression ="^[1-9]\d*$" ControlToValidate ="TextBox2" runat="server" ErrorMessage="Invalid data"></asp:RegularExpressionValidator>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" />
</div>
</form>
<script type="text/javascript">
function Validate(sender, args) {
if (document.getElementById(sender.controltovalidate).value != "") {
args.IsValid = true;
} else {
args.IsValid = false;
}
}
</script>
<script type="text/javascript">
function WebForm_OnSubmit() {
if (typeof (ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) {
for (var i in Page_Validators) {
try {
var control = document.getElementById(Page_Validators[i].controltovalidate);
alert(i);
alert(Page_Validators[i].isvalid);
if (!Page_Validators[i].isvalid) {
control.className = "ErrorControl";
} else {
control.className = "";
}
} catch (e) { }
}
return false;
}
return true;
}
</script>
</body>
</html>
答案 0 :(得分:1)
RegularExpressionValidator
不检查空字符串 - 他们将其留给RequiredFieldValidator
。
当您同时拥有两个验证器时,RequiredFieldValidator
会设置className="ErrorControl"
,但RegularExpressionValidator
会将其重置为className=""
。这就是它不改变边框颜色的原因。
一个相当干净和简单的方法是在检查验证器之前从表单中删除所有ErrorControl
类,然后将其添加到无效的类中:
function WebForm_OnSubmit() {
if (typeof (ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) {
// find and remove all .ErrorControl classes
var errorControls = document.querySelectorAll('.ErrorControl');
for (var ec = 0; ec < errorControls.length; ec++) {
errorControls[ec].className = "";
}
for (var i in Page_Validators) {
try {
var control = document.getElementById(Page_Validators[i].controltovalidate);
alert(i);
alert(Page_Validators[i].isvalid);
if (!Page_Validators[i].isvalid) {
control.className = "ErrorControl";
} // no need to remove ErrorControl if valid
} catch (e) { }
}
return false;
}
}