Friday, February 6, 2009

How to manage ASP.NET validation from Javascript with jQuery

 

Just an example from the original article, but it is self explanatory

 
 
<asp:DropDownList ID="ddlMimeType" runat="server">
   <asp:ListItem Value="mp3">audio/mpeg</asp:ListItem>
   <asp:ListItem Value="wma">audio/wma</asp:ListItem>
   <asp:ListItem Value="other">Other</asp:ListItem>
</asp:DropDownList>
<asp:TextBox id="txbOtherMimetype" runat="server" />
<asp:RequiredFieldValidator id="valOtherMimetypeRequired" runat="server"
                   ControlToValidate="txbOtherMimetype" ForeColor="#990066"
                   ErrorMessage="You have to specify a custom mimetype." />
 

 

<script type="text/javascript">
$(document).ready(function()
{
  $("#<%= ddlMimeType.ClientID %>").change(function() 
  {
    toggleOtherMimeType(this);
  });
}
 
function toggleOtherMimeType(elem)
{
  if(elem!=undefined) 
  {
    if(elem.value=="other")
    {
      $("#<%= txbEnclosureOtherMimetype.ClientID %>").show();
      ValidatorEnable($("#<%= valEncOtherMimetypeRequired.ClientID %>")[0], true);
    }
    else
    {
      $("#<%= txbEnclosureOtherMimetype.ClientID %>").hide();
      ValidatorEnable($("#<%= valEncOtherMimetypeRequired.ClientID %>")[0], false);
    }
  }
}
</script>

 

Source