[英]Asp.Net custom validation control not showing error messages
以下代碼用於驗證何時按下表單提交按鈕,但我沒有得到想要的結果。
它應該顯示錯誤消息,但沒有顯示,我在做什么錯?
定制驗證器驗證密碼,它應該根據發生的錯誤來更改錯誤消息:
一次只能顯示一個錯誤,因此我在.ascx.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;
將被執行。 在這種情況下,您的文本框將是有效的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.