NoStressDeveloper
NoStressDeveloper

Reputation: 533

How to validate that user enter only current or previous MM/YYYY and not future MM/YYYY

I am trying to do validation on textbox "TextBoxToMonth" such that user enter only current or previous MM/YYYY and not enter future MM/YYYY.

So user can enter dates like 09/2015 and not able to submit future dates like 09/2030. I am using below comparevalidator. But I am not sure what to enter in ValueToCompare property.How do I achieve this validation?

     <asp:CompareValidator ControlToValidate="TextBoxToMonth" 
                Type="Date" runat="server" ID="cvToMonth" Display="None"  ValidationGroup="RepGroup" 
 ErrorMessage="<b>Invalid Date Range</b><br />You must enter a End Month that is less than or equal to Current Month." 
        Operator="LessThanEqual"  ValueToCompare="<%# DateTime.Today.ToShortDateString() %>">
    </asp:CompareValidator>

Upvotes: 1

Views: 449

Answers (1)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241728

You can't do this in a CompareValidator. You'll need to use a CustomValidator instead.

<asp:CustomValidator runat="server" ControlToValidate="YourTextBox"
                     ErrorMessage="YourErrorMessage" OnServerValidate="OnServerValidate" />
protected void OnServerValidate(object source, ServerValidateEventArgs args)
{
    DateTime dt;
    args.IsValid = DateTime.TryParseExact(args.Value, "MM/yyyy",
        CultureInfo.InvariantCulture, DateTimeStyles.None, out dt) 
        && dt <= DateTime.Today;
}

One minor but important detail - since "today" isn't the same all over the world at the same time, it's possible that DateTime.Today when run on your server could be a different date than the one the end-user is observing. If you are at the end of the month, and they're on the first of the next month, then this test will fail.

To validate perfectly, you would need to know the time zone of the end-user. Alternatively, you could add an extra day to err on the other side.

Upvotes: 1

Related Questions