我为 RadioButtonList 使用 CustomValidator,而不是 RequiredFieldValidator,这样我就可以使用 Javascript 分配一个 CSS 类。验证是检查是否至少选择了一个项目。下一个。代码不起作用:
JS:
function validateRadioButtonList() {
var target = document.getElementById('<%=rbGender.ClientID %>');
var radioButtons = target.getElementsByTagName('input');
var is_valid;
if (radioButtons[0].checked || radioButtons[1].checked) {
is_valid = true;
target.className = "";
}
else {
target.className = "validate";
is_valid = false;
}
args.IsValid = is_valid;
}
ASPX:
<asp:RadioButtonList ID="rbGender" runat="server" RepeatDirection="Horizontal"
RepeatLayout="Flow" AutoPostBack="false">
<asp:ListItem>Male </asp:ListItem>
<asp:ListItem>Female </asp:ListItem>
</asp:RadioButtonList>
<asp:CustomValidator ID="CustomValidator3" runat="server"
ControlToValidate="rbGender" ClientValidationFunction="validateRadioButtonList"
Text="*" ForeColor="Red"> </asp:CustomValidator>
<asp:Button ID="btnUpdate" runat="server" Text="Update"
ValidationGroup="vsGroup" />
生成的 HTML:
<div class="">
<span id="ContentPlaceHolder1_rbGender">
<input id="ContentPlaceHolder1_rbGender_0" type="radio"
name="ctl00$ContentPlaceHolder1$rbGender" value="Male " />
<label for="ContentPlaceHolder1_rbGender_0">Male </label>
<input id="ContentPlaceHolder1_rbGender_1" type="radio"
name="ctl00$ContentPlaceHolder1$rbGender" value="Female " />
<label for="ContentPlaceHolder1_rbGender_1">Female </label>
</span>
<span style="float: right; margin-right: 3%">
<span id="ContentPlaceHolder1_CustomValidator3" style="color:Red;
visibility:hidden;">* </span>
</span>
</div>
但如果我包括
UseSubmitBehavior="False" OnClientClick="validateRadioButtonList()"
对于按钮,它可以工作。我不想这样做。