ASP.NET validator for comparing two differences by date no more than 12 months

I have two elements TextBoxfor entering a start and end date for a date. I must confirm that the end date is not more than the start date, and the difference between the start date and the end date is not more than 12 months.

+3
source share
4 answers

For this you will need to use CustomValidator. 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 a 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 , , .

, , , ( ) . , , .

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

Timespan:

        DateTime start = DateTime.Parse(DateBegin.Text);
        DateTime end = DateTime.Parse(DateEnd.Text);
        TimeSpan ts = end - start;
        e.IsValid = ts.Days < 365;
+1

: , - ( ) .

0
source

And why aren't you talking about this

 DateTime start = DateTime.Parse(DateBegin.Text);
 DateTime end = DateTime.Parse(DateEnd.Text);
 e.IsValid = (end-start).Years <1;
0
source

Source: https://habr.com/ru/post/1733855/


All Articles