简体   繁体   中英

ASP.NET: skip running CompareValidator if some other field is not empty

My search form has 2 fields: Date and Object id. i'm using date validation like this:

<asp:CompareValidator ID="cv" runat="server" Operator="GreaterThanEqual" Type="Date"
                                ControlToValidate="dateControl" ValueToCompare="" Display="None" SetFocusOnError="False"
                                ErrorMessage="error msg" EnableClientScript="True"/>

ValueToCompare is set from code-behind (10 days back from now).

i don't want to run date validation, when Object id field is not empty (allows to search without date restrictions). What are solutions without using CustomValidator?

Check this.may be this help you:

if(!string.IsNullOrEmpty(Objectid.Text))
 cv.ValueToCompare=DateTime.Now.AddDays(1);
else
 cv.ValueToCompare=DateTime.Now.AddDays(-10);

Simply set the 'Enabled' property to false in Code behind file. The Validation is performed after the Page.Load event but just before the event fires for the button or control that triggered the validation.

// Markup portion

<asp:CompareValidator ID="cv" runat="server" Operator="GreaterThanEqual" Type="Date"
ControlToValidate="dateControl" ValueToCompare="" Display="None" SetFocusOnError="False"
ErrorMessage="error msg" EnableClientScript="True"/>

// Code behind file

protected void Page_Load(object sender, EventArgs e)
    {
        if(!String.IsNullOrEmpty(ObjectId.Text))
         {
             cv.Enabled=false;
         }
    }

Now, when the Validation will be performed, CompareValidator will be skipped. You can also set the 'Visible' property to false as a second option. Check the MSDN here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM