你如何检查这两个日期是否在同一年和同一年?我应该使用哪个验证控件来实现它?我正在考虑使用客户端验证(如果可能的话)
谢谢!
你可以使用一个CustomValidator
aspx:
<asp:CustomValidator runat="server"
ID="valMonth"
onservervalidate="ServerValidation"
onclientvalidate="ClientValidate"
ErrorMessage="From and To must be in the same month" />
服务器验证:
protected void ServerValidation (object source, ServerValidateEventArgs args)
{
DateTime dtFrom;
DateTime dtTo;
if(DateTime.TryParse(TxtFrom.Text, out dtFrom) && DateTime.TryParse(TxtTo.Text, out dtTo))
{
args.IsValid = dtFrom.Year == dtTo.Year && dtFrom.Month == dtTo.Month;
}
else
{
args.IsValid = false;
}
}
您还应该添加两个CompareValidators
检查两者是否都是有效日期。要提供一个ClientValidationFunction
,您可以查看getMonth
和getFullYear
功能。
例如(未测试):
<script language="javascript">
<!--
function ClientValidate(source, arguments)
{
var txtFrom = document.getElementById('<%= TxtFrom.ClientID %>');
var txtTo = document.getElementById('<%= txtTo.ClientID %>');
var dtFrom = new Date(txtFrom.value);
var dtTo = new Date(txtTo.value);
var monthFrom = dtFrom.getMonth();
var monthTo = dtTo.getMonth();
var yearFrom = dtFrom.getFullYear();
var yearTo = dtTo.getFullYear();
arguments.IsValid = yearFrom == yearTo && monthFrom == monthTo;
}
// -->
</script>
假设日期采用“dd/MM/yyyy”格式,您可以将此 javascript 函数与自定义验证器一起使用。
aspx
<asp:CustomValidator ID="CustomValidator1" runat="server"
EnableClientScript="true"
ErrorMessage="ERROR MESSAGE HERE"
ClientValidationFunction="checkDate">
</asp:CustomValidator>
javascript
function checkDate() {
var date1=document.getElementById('<%=txtDate1.ClientID%>').value;
var date2=document.getElementById('<%=txtDate1.ClientID%>').value;
var date1Values=date1.split("/");
var date2Values=date2.split("/");
if (date1Values[2] == date2Values[2] && date1Values[1] ==date2Values[1]) {
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
如果禁用了 javascript,您也应该有服务器验证代码。见蒂姆的回答。
这是一个使用CustomValidator控件的简短示例
Date 1<asp:TextBox ID="txtDate1" runat="server" />
<br />
Date 2<asp:TextBox ID="txtDate2" runat="server" />
<br />
<asp:Button ID="btnCompare" runat="server" Text="Compare" />
<asp:CustomValidator ID="dateValidator" runat="server" ErrorMessage="The two dates must be in the same month and year"
OnServerValidate="ValidateDate" />
<script runat="server">
protected void ValidateDate(object source, ServerValidateEventArgs args)
{
DateTime date1 = DateTime.Parse(txtDate1.Text);
DateTime date2 = DateTime.Parse(txtDate2.Text);
if (date1.Month != date2.Month || date1.Year != date2.Year)
args.IsValid = false;
}
</script>