我正在尝试使用RequiredFieldValidator验证文本框,并通过代码隐藏在ValidationSummary中显示错误消息,但我无法做到这一点。 我的代码在这里
if (txtUsrName.Text.Length == 0 || txtUsrAge.Text.Length == 0)
{
RequiredFieldValidator req = new RequiredFieldValidator();
req.ID = "Required";
req.ControlToValidate = txtUsrName.ID;
req.IsValid = false;
req.Visible = true;
req.Enabled = true;
req.ValidationGroup = "ValidationGroup";
req.ErrorMessage = "Thease are required fields";
req.InitialValue = "";
req.Text = "*";
ValidationSummary valsum = new ValidationSummary();
ValidationSummaryDisplayMode mode = new ValidationSummaryDisplayMode();
valsum.ID = "validatesummury";
valsum.HeaderText = "please correct the following errors";
valsum.DisplayMode = mode;
valsum.ShowSummary = true;
valsum.ValidationGroup = "ValidationGroup";
valsum.Visible = true;
}
请帮我解决这个问题
答案 0 :(得分:2)
您可以使用Page.Validate() OR Page.Validate("YOUR_VALIDATION_GROUP")
然后检查Page.IsValid
以检查所有验证器是否有效,对于特殊验证器,您也可以使用YOUR_RequiredFieldValidator.IsValid
'YOUR_RequiredFieldValidator' is one attached to your textbox control
答案 1 :(得分:0)
以下是一个类似的问题,可能会为您提供见解:Unobtrusive Validation in Webforms using Data Annotations。数据注释提供了检查类属性的长度,最小值/最大值等的方法。