When processing validation, I would use ASP.net custom validators and use jquery for assis with client-side validation:
Asp.net aspx
<form id="form1" runat="server"> <div> <div id="requiedCheck1" class="check"> <asp:RadioButton ID="radio1" runat="server" GroupName="myGroup" /> <asp:TextBox ID="text1" runat="server" Disabled="true"></asp:TextBox> <asp:CustomValidator ID="val1" runat="server" ErrorMessage="Please Enter Text" ClientValidationFunction="ValidateSomething" ControlToValidate="text1" ValidateEmptyText="true" ></asp:CustomValidator> </div> <div id="requiedCheck2" class="check"> <asp:RadioButton ID="radio2" runat="server" GroupName="myGroup" /> <asp:TextBox ID="text2" runat="server" Disabled="true"></asp:TextBox> <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please Enter Text" ClientValidationFunction="ValidateSomething" ControlToValidate="text2" ValidateEmptyText="true"></asp:CustomValidator> </div> <asp:button ID="Button1" runat="server" text="Button" /> </div> </form>
Please note that I set ValidateEmptyText to true .
Validation function
function ValidateSomething(sender, args) { args.IsValid = false; var parentDiv = $(sender).parent(".check"); var radioChecked = $(parentDiv).find("input:radio").is(":checked"); var hasText = $(parentDiv).find("input:text").val().length > 0; if (radioChecked) { args.IsValid = hasText; } else { args.IsValid = true; } }
I would also add a server side validation method.
If you want to get really fantasy, you can also connect radio buttons. This will start the test when checking the radio volumes.
$(document).ready(function () { //Wire up the radio buttons to trigger validation this is optional $(".check input:radio").each(function () { ValidatorHookupControlID($(this).attr('id'), document.getElementById("<%= val1.ClientID %>")); ValidatorHookupControlID($(this).attr('id'), document.getElementById("<%= val2.ClientID %>")); }); //jquery to change the disabled state $(".check :radio").click(function(){ var parDiv = $(this).parent(".check"); //get parent div //empty text and set all to disabled $(".check input:text").val("").prop("disabled", true); //set target to enabled $(parDiv).find("input:text").prop("disabled", false); }); });
I added javascript jQuery to switch the state of disabled text fields. You can see the switch in action here: http://jsfiddle.net/cVACb/
Jon p
source share