目标
无需我实际启动验证即可进行验证。
代码
input
我用这个用户控件标记了一个元素:
<vbp:DataRowTextBox ID="SecurityAnswer" runat="server" IsRequired="true"
RequiredErrorMessage="Please enter an answer for your security question." MaxLength="50"
Label="Your Answer" />
谁的内部标记是这样的:
<input type="text" id="textBox" runat="server" />
<asp:RequiredFieldValidator ID="requiredFieldValidator" CssClass="errorMessage" Display="None"
EnableClientScript="false" Text=" " ValidationGroup="LHError" runat="server"
ControlToValidate="textBox" />
<asp:RegularExpressionValidator ID="regexValidator" CssClass="errorMessage" Display="None"
EnableClientScript="false" Text=" " ValidationGroup="LHError" runat="server"
ControlToValidate="textBox" />
<asp:CompareValidator ID="compareValidator" CssClass="errorMessage" Display="None"
EnableClientScript="false" Text=" " ValidationGroup="LHError" runat="server"
ControlToValidate="textBox" />
<asp:CustomValidator ID="customValidator" CssClass="errorMessage" Display="None"
EnableClientScript="false" Text=" " ValidationGroup="LHError" runat="server"
ControlToValidate="textBox" />
<asp:RangeValidator ID="rangeValidator" CssClass="errorMessage" Display="None"
EnableClientScript="false" Text=" " ValidationGroup="LHError" runat="server"
ControlToValidate="textBox" />
在用户控件中打开和关闭验证器的代码如下所示:Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (this.ClientIDMode == ClientIDMode.Static)
{
this.textBox.ID = this.ID;
}
this.label.Attributes.Add("for", this.textBox.ClientID);
this.label.InnerHtml = string.Format("{0}:{1}", this.Label, EmitRequiredSup());
this.requiredFieldValidator.Visible = this.IsRequired;
this.regexValidator.Visible = (this.Regexes != null);
if (this.regexValidator.Visible)
{
var regexes = string.Join("|", this.Regexes);
this.regexValidator.ValidationExpression = regexes;
}
this.compareValidator.Visible = !string.IsNullOrEmpty(this.ControlToCompare);
this.rangeValidator.Visible = !string.IsNullOrEmpty(this.RangeMinimumValue);
this.requiredFieldValidator.ControlToValidate = this.textBox.ID;
this.regexValidator.ControlToValidate = this.textBox.ID;
this.compareValidator.ControlToValidate = this.ID;
this.customValidator.ControlToValidate = this.textBox.ID;
this.rangeValidator.ControlToValidate = this.textBox.ID;
}
因此,在此示例中,我将打开所需的验证器,因为我将IsRequired
属性设置为 true。但是,当我这样标记时LinkButton
:
<asp:LinkButton CssClass="actionButton" ID="Submit" runat="server" OnClick="Submit_Click" ValidationGroup="LHError">Change Security Question</asp:LinkButton>
当前结果
我被迫打电话Validate
来进行验证。我究竟做错了什么?我想用CausesValidation
set to true
(这是 a 的默认值LinkButton
)和ValidateGroup
定义的,它会在页面加载后自动运行验证。
并且非常简洁,在按钮的点击事件中,即使有无效数据,直到我调用.IsValid
true
Validate