你可以使用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" />