How not to trigger RequiredFieldValidator on hidden field (TextBox)

I think this is a common problem. I have a form where I show/hide fields dynamically using jQuery, depending on some radio buttons.

I have RequiredFieldValidator’s on all the fields, but I don’t want them to be triggered if their ControlToValidate is hidden (using jQuery).

Is that possible? Thanks in advance.

EDIT: Here is the solution, thanks to Marek. It might not be very obvious if you have weird clientIDs because of MasterPages

This is the ASPX

<asp:TextBox ID="txtName" runat="server" />
<asp:RequiredFieldValidator ID="vldName" ControlToValidate="txtName" runat="server" ErrorMessage="You must enter Name!" />
...
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />

This is the jQuery

$(function() {
  $('#ctl00_cphContent_btnSubmit').click(function() {
    if (!$('#ctl00_cphContent_txtName').is(':visible'))
      ValidatorEnable(ctl00_cphContent_vldName, false);
  });
});

Hope it will make someone’s life easier

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

If I remember correctly there’s a function called ValidatorEnable(validatorClientId, isEnabled) that allows you to disable/enable the ASP.NET validators via javascript. You could use jQuery right before your form submit to disable all your invisible validators.

There’s some documentation about client side API available from the validators here http://msdn.microsoft.com/en-us/library/aa479045.aspx

Method 2

Hey u can set the control to validate property from C# code when u r setting visiblility from C# code.This wil solves ur problem.

if ($('#input-name').length) {  
       // do something

}

This will now solves ur problem


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x