简体   繁体   中英

How to bypass Asp.net control validation only for few control on button click?

I have an ASP.NET form that takes input from a user. There is a Save & Add button on the form to perform different functionalities.

The problem I'm having is that on the form I have a set of validators and when the Add button is pressed the form gets validated. There are 5 controls on the page but during Add button click , I need to validate only two controls. Only during Save button click, I should validate all controls.

How to ignore those 3 control validation during Add button click.

Any way around this?

To skip some of the validations I suppose you might want to use ValidatorEnable method in jquery to enable/disable. Something like this :

Email:
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="valEmail" ControlToValidate="txtEmail" runat="server" 
     ErrorMessage="*Required" ForeColor="Red" ValidationGroup="Group2" />
<br />
Enable Validation:
<input type="checkbox" id="CheckBox2 checked="checked" />
<br />
<asp:Button Text="Submit" runat="server" ValidationGroup="Group2" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(document).on("click", "#CheckBox2", function () {
        var valEmail = $("[id*=valEmail]");
        ValidatorEnable(valEmail[0], $(this).is(":checked"));
    });
</script>

Here is the live Demo in case you want to test it before heading towards its implementation: https://www.aspsnippets.com/demos/642/

EDIT

To achieve this task using pure javascript and not jquery you can do something like this:

ValidatorEnable(document.getElementById('<%=yourValidator.ClientID%>'), false);

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