以下代碼用於驗證表單提交按鈕何時被命中,但我沒有收到想要的結果。Asp.Net自定義驗證控件不顯示錯誤消息
它應該顯示錯誤消息,但它們沒有被顯示我做錯了什麼?
自定義驗證驗證密碼,它應根據所發生的錯誤更改錯誤信息:
- 密碼爲空
- 密碼無效
- 密碼不匹配
一次只能顯示一個錯誤,所以我在.ascx.cs中編寫了這個自定義validator:
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>
你的問題是什麼?驗證器是否無效,請解釋發生了什麼/出錯,併發布實際使用驗證器的標記。 –
錯誤消息不會顯示,我不確定如何正確調試驗證器想要了解我剛剛獲得的標記。 – Anicho
一旦你設置了'cvPasswordValidation.IsValid = false;'在任何情況下,你能不能從處理程序中返回? – NaveenBhat