您可以将 CustomValidators 用于任何事情,它们是我的最爱!
如果您使用 HTML5 属性,required="required"
您可以免费获得客户端反馈。
您还可以利用它们来执行服务器端验证,如下所示:
<asp:ValidationSummary runat="server" id="vSummary" />
<asp:TextBox runat="server" id="txtReq" required="required" />
<asp:DropDownList runat="server" id="ddlReq" required="required">
<asp:ListItem text="..." value="" />
<asp:ListItem text="Yes" value="1" />
<asp:ListItem text="No" value="0" />
</asp:DropDownList>
<asp:Button runat="server" id="cmdSubmit" text="Submit" />
函数背后的代码:
private void buildRequiredWebControls(List<WebControl> lst, Control c)
{
if (c is WebControl)
if (String.Compare((c as WebControl).Attributes["required"] ?? String.Empty, "required", true) == 0)
lst.Add((c as WebControl));
foreach (Control ch in c.Controls)
buildRequiredWebControls(lst, ch);
}
/* --------------------------------------------- */
private Boolean addAllFieldsRequired(List<WebControl> controls)
{
foreach (WebControl w in controls)
{
if (w as TextBox != null)
if (String.IsNullOrWhiteSpace((w as TextBox).Text)) return false;
if (w as DropDownList != null)
if (String.IsNullOrWhiteSpace((w as DropDownList).SelectedValue)) return false;
}
return true;
}
/* --------------------------------------------- */
private void cmdSubmit_Click(object sender, EventArgs e)
{
vSummary.ValidationGroup = "StackOverflow";
Page.Validate("StackOverflow");
List<WebControl> requiredFields = new List<WebControl>();
this.buildRequiredWebControls(requiredFields, this);
Page.Validators.Add(new CustomValidator()
{
IsValid = this.addAllFieldsRequired(requiredFields),
ErrorMessage = "Please complete all required fields.",
ValidationGroup = "StackOverflow"
});
if (Page.IsValid)
{
//Good to Go on Required Fields
}
}
击败非常单调的替代方案,即在每个控件之后手动将它们插入到 html 中:
<asp:ValidationSummary runat="server" id="vSummary" ValidationGroup="StackOverflow" />
<asp:TextBox runat="server" id="txtReq" required="required" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtReq" ErrorMessage="Please Fill Out Required Field" Text="*" ValidationGroup="StackOverflow" />
<asp:DropDownList runat="server" id="ddlReq" required="required">
<asp:ListItem text="..." value="" />
<asp:ListItem text="Yes" value="1" />
<asp:ListItem text="No" value="0" />
</asp:DropDownList>
<asp:RequiredFieldValidator runat="server" ControlToValidate="ddlReq" ErrorMessage="Please Fill Out Required Field" Text="*" ValidationGroup="StackOverflow" />
<asp:Button runat="server" id="cmdSubmit" text="Submit" />