Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude a control from ASP.NET validation when hidden (display:none;)?

HOW TO EXCLUDE A CONTROL FROM ASP.NET VALIDATION WHEN HIDDEN?

  • A checkbox is used to alternate between two textboxs.

  • Either one or the other is required NOT BOTH.

  • I want the required field to disabled when hidden.

I am aware enabled="false" and visible="false" create this behaviour however I want to maintain the jquery fade in out animation.

I tried to add disabled false property to javascript but couldn't get it to work. Other solutions found online don't seem to achieve what is needed.

ASP.NET

<div class="Hide1">
  <asp:TextBox ID="tb" runat="Server"/>
  <asp:RequiredFieldValidator ID="rfv1" RunAt="Server" ControlToValidate="tb"/>
</div>

<div class="Hide2">
  <asp:TextBox ID="tb2" runat="Server"/>
  <asp:RequiredFieldValidator ID="rfv2" RunAt="Server" ControlToValidate="tb2"/>
</div>

<asp:Button ID="btn" runat="Server" Text="GO"/>

JQUERY

  $('.tb').hide();
  $('#CB').change(function () {
    if ($(this).is(':checked')) {
      $('.tb2').fadeOut(100, function () {
        $('.tb').fadeIn();
      });
    } else {
      $('.tb').fadeOut(100, function () {
        $('.tb2').fadeIn();
      });
    }
  });
like image 905
DreamTeK Avatar asked Mar 06 '26 15:03

DreamTeK


1 Answers

You can try something like this

if (document.getElementById('<%=CB.ClientID%>').checked) {
   ValidatorEnable(document.getElementById('<%= rfv1.ClientID %>'), true);
   ValidatorEnable(document.getElementById('<%= rfv2.ClientID %>'), false);
   $('.tb2').fadeOut(100, function () {
        $('.tb').fadeIn();
      });
 }
 else {
       ValidatorEnable(document.getElementById('<%= rfv1.ClientID %>'), false);
       ValidatorEnable(document.getElementById('<%= rfv2.ClientID %>'), true);
       $('.tb').fadeOut(100, function () {
          $('.tb2').fadeIn();
          });
      }

Note: rfv1 and rfv2 are the id's of the two required validators and please avoid giving same id to validators.

Update

if (document.getElementById('<%=CB.ClientID%>').checked) {
       ValidatorEnable(document.getElementById("#<%= rfv1.ClientID %>"), true);
       ValidatorEnable(document.getElementById("#<%= rfv2.ClientID %>"), false);
       $('.tb2').fadeOut(100, function () {
            $('.tb').fadeIn();
          });
     }
     else {
           ValidatorEnable(document.getElementById("#<%= rfv1.ClientID %>"), false);
           ValidatorEnable(document.getElementById("#<%= rfv2.ClientID %>"), true);
           $('.tb').fadeOut(100, function () {
              $('.tb2').fadeIn();
              });
          }
like image 187
Sid M Avatar answered Mar 08 '26 04:03

Sid M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!