使用 CustomeValidator 控件并将 ClientValidationFunction 属性设置为 javascript/jquery 函数。js 函数可能看起来像这样 -
<script language="JavaScript">
<!--
function CheckDate(sender, args)
{
var strDate = $(fromdatetextbox).val();
var dateParts = strDate.split("/");
var fromdate = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
strDate = $(todatetextbox).val();
dateParts = strDate.split("/");
todate = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
if(fromdate > todate)
args.IsValid = false;
else
args.IsValid = true;
}
// -->
</script>
您可以在此链接中了解有关 customvalidator 的更多信息
http://www.4guysfromrolla.com/articles/073102-1.aspx
更新
这是完整代码的样子
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
<!--
function CheckDate(sender, args) {
var strDate = $('#<%= textBoxFromDate.ClientID %>').val();
var dateParts = strDate.split("/");
var fromdate = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
strDate = $('#<%= textBoxToDate.ClientID %>').val();
dateParts = strDate.split("/");
todate = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
if (fromdate > todate)
args.IsValid = false;
else
args.IsValid = true;
}
// -->
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="textBoxFromDate" runat="server" Text=""></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="CustomValidator"
ControlToValidate="textBoxFromDate" ClientValidationFunction="CheckDate"></asp:CustomValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator"
ControlToValidate="textBoxFromDate"></asp:RequiredFieldValidator>
<asp:TextBox ID="textBoxToDate" runat="server" Text=""></asp:TextBox>
<asp:CustomValidator ID="CustomValidator2" runat="server" ErrorMessage="CustomValidator"
ControlToValidate="textBoxToDate" ClientValidationFunction="CheckDate"></asp:CustomValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="RequiredFieldValidator"
ControlToValidate="textBoxToDate"></asp:RequiredFieldValidator>
</div>
</form>
</body>
</html>