Asp.Net自定义验证控件不显示错误消息
本文关键字:显示 错误 消息 控件 Net 自定义 验证 Asp | 更新日期: 2023-09-27 18:06:41
下面的代码用于验证何时点击表单提交按钮,但是我没有得到想要的结果。
它应该显示错误消息,但他们没有被显示我做错了什么?
自定义验证器验证密码,它应该根据发生的错误更改错误消息:
- 密码为空
- 密码无效
- 密码不匹配
一次只能显示一个错误,所以我在. asx .cs中编写了这个自定义验证器:
protected void cvPasswordValidation_ServerValidate(object source, ServerValidateEventArgs args)
{
bool IsPasswordBlank = false;
bool IsPasswordValid = false;
cvPasswordValidation.IsValid = false;
// If password is blank then IsValid is false, show blank password errors.
if (String.IsNullOrEmpty(args.Value))
{
//args.IsValid = false;
IsPasswordBlank = true;
//Show blank password error depending on which box is empty.
if (String.IsNullOrEmpty(txtPassword.Text))
{
cvPasswordValidation.ErrorMessage = "You must enter password";
}
else
{
cvPasswordValidation.ErrorMessage = "You must confirm password";
}
cvPasswordValidation.IsValid = false;
}
else
{
cvPasswordValidation.IsValid = true;
}
// If password is not valid format then IsValid is false, show invalid format errors.
if (!Regex.IsMatch(args.Value, RegexHelper.ValidPassword))
{
IsPasswordValid = true;
//Show invalid format errors, if password is not blank
if (IsPasswordBlank == false)
{
cvPasswordValidation.ErrorMessage = "<b>Current password</b> not in correct format. Your password must contain 6 - 12 characters with a combination of numbers and letters.";
}
cvPasswordValidation.IsValid = false;
}
else
{
cvPasswordValidation.IsValid = true;
}
// If passwords do not match then IsValid is false, show do not match errors.
bool areEqual = String.Equals(txtPassword.Text, txtConfirmPassword.Text, StringComparison.Ordinal);
if (areEqual == false)
{
//Show do not match errors is password is not blank and is not invalid format
if (IsPasswordBlank == false && IsPasswordValid == false)
{
cvPasswordValidation.ErrorMessage = "Your passwords do not match.";
}
cvPasswordValidation.IsValid = false;
}
else
{
cvPasswordValidation.IsValid = true;
}
}
和。ascx:
<asp:TextBox runat="server" ID="txtPassword" MaxLength="12" autocomplete="off" TextMode="Password" ValidationGroup="vgOnlineDetails"></asp:TextBox>
<asp:CustomValidator ID="cvPasswordValidation"
runat="server"
display="Dynamic"
OnServerValidate="cvPasswordValidation_ServerValidate"
ControlToValidate="txtPassword"
ValidationGroup="vgOnlineDetails">
</asp:CustomValidator>
您需要设置ValidateEmptyText = true来验证空字段
您应该在分配给IsValid属性后使用return
。当您根本没有指定密码时的条件。如果在赋值后没有指定return
,则将执行所有三个if
语句。在最后的if
中,areEqual
变量将是true
,因为两个空字符串是相等的,cvPasswordValidation.IsValid = true;
将被执行。在这种情况下,您的文本框将有效。