Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

asp.net - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...