本文介绍了ASP.NET验证器来比较两个日期的差异不超过12个月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 TextBox 控件,用于开始日期&结束日期输入。我必须确认结束日期不大于开始日期&开始日期与结束日期不超过12个月。

I have two TextBox controls for start date & end date input. I have to validate that end date is not greater than start date & the difference between start date & end date is not more than 12 months.

推荐答案

您将必须使用来执行此操作。在您的markyou中,您将具有以下内容:

You will have to use a CustomValidator to do this. In your markyou, you will have something like this:

<asp:TextBox ID="txbStartDate" runat="server" />
<asp:TextBox ID="txbEndDate" runat="server" />
<asp:CustomValidator OnServerValidate="ValidateDuration"
    ErrorMessage="Dates are too far apart" runat="server" />

在后面的代码中,您定义验证处理程序:

And in your code behind, you define the validation handler:

protected void ValidateDuration(object sender, ServerValidateEventArgs e)
{
    DateTime start = DateTime.Parse(txbStartDate.Text);
    DateTime end = DateTime.Parse(txbEndDate.Text);

    int months = (end.Month - start.Month) + 12 * (end.Year - start.Year);

    e.IsValid = months < 12.0;
}

请注意,上面的代码容易引发异常 >。您将需要添加其他验证器,以检查输入的日期是否可以解析,并且应修改 ValidateDuration 方法以确认这些其他验证器在通过自己的测试之前已通过

Note that the code above is prone to throw exceptions. You will need to add additional validators to check that the dates entered can be parsed, and the ValidateDuration method should be modified to confirm that these other validators have passed before doing its own tests.

此外,您可能还想添加另一个验证器来测试结束日期实际上是否大于(或等于)开始日期。违反此规则可能会引发自己的验证错误消息。

Further, you might want to yet add another validator to test that the end date is in fact greater (or equal to) the start date. Breaking this rule should probably raise its own validation error message.

<asp:CompareValidator Operator="GreaterThanEqual" Type="Date"
    ControlToValidate="txbEndDate" ControlToCompare="txbStartDate"
    ErrorMessage="Let's get started first!" runat="server" />

这篇关于ASP.NET验证器来比较两个日期的差异不超过12个月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 23:43