ASP.NET validator to compare two date difference i

2019-05-14 16:20发布

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.

4条回答
叛逆
2楼-- · 2019-05-14 16:32

Quick and easy: Two validators, one a Comparison Validator (which compares both controls), and a Custom Validator with a server-side method to check the end date.

查看更多
虎瘦雄心在
3楼-- · 2019-05-14 16:35

Also you can use Timespan:

        DateTime start = DateTime.Parse(DateBegin.Text);
        DateTime end = DateTime.Parse(DateEnd.Text);
        TimeSpan ts = end - start;
        e.IsValid = ts.Days < 365;
查看更多
走好不送
4楼-- · 2019-05-14 16:46

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;
}

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" />
查看更多
beautiful°
5楼-- · 2019-05-14 16:46

And why you're not about that

 DateTime start = DateTime.Parse(DateBegin.Text);
 DateTime end = DateTime.Parse(DateEnd.Text);
 e.IsValid = (end-start).Years <1;
查看更多
登录 后发表回答