处理验证,我会使用 ASP.net 自定义验证器并使用 jquery 来协助客户端验证:
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>
请注意,我已设置ValidateEmptyText
为true
.
js验证函数
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;
}
}
我还将添加一个服务器端验证方法。
如果你想变得非常花哨,你也应该能够连接单选按钮。这将在选中单选按钮时触发验证
$(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);
});
});
我添加了 jQuery javascript 来切换文本框的禁用状态。您可以在此处查看切换操作:http: //jsfiddle.net/cVACb/