19

我以前遇到过这个问题,但从来没有完全解决过。我有一个包含多个验证器和一个 CustomValidator 的表单。

<asp:Label ID="lblMemberNum" runat="server" Text="Membership #:" CssClass="LabelMedium"  ></asp:Label>
<asp:TextBox ID="txtMemberNum" runat="server" CssClass="TextBox" ></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvMemberNum" SetFocusOnError="True" runat="server"
    ControlToValidate="txtMemberNum" ErrorMessage="[ Membership # ] is required"
    CssClass="ValidationMessage" Display="Dynamic" >*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revMemberNum"  Display="Dynamic" runat="server" 
    ControlToValidate="txtMemberNum" CssClass="ValidationMessage" 
    ErrorMessage="[ Membership # ] can only contain letters" 
    ValidationExpression="^([a-zA-Z\d]+)$" >*</asp:RegularExpressionValidator>
<asp:CustomValidator ID="cvMemberNum" runat="server" 
    CssClass="ValidationMessage" Display="Dynamic"
    ControlToValidate="txtMemberNum" ValidateEmptyText="false"
    OnServerValidate="cvMemberNum_Validate" 
    ErrorMessage="This membership number is already registered">*</asp:CustomValidator>

<asp:ValidationSummary ID="ValidationSummary1" runat="server" 
    CssClass="ValidationMessage" 
    ShowMessageBox="True" ShowSummary="False" />

在服务器端:

protected void cvMemberNum_Validate(object source, ServerValidateEventArgs args)
{
    try
    {
        args.IsValid  = (!CampaignRegistration.IsMemberRegistered(args.Value));
    }
    catch
    {
        args.IsValid = false;
    }
}

我的问题是:ValidationSummary 从不显示来自 CustomValidator 的消息。这个问题在很多地方都被问过,但我还没有看到满意的答案。

4

7 回答 7

10

尝试在所有验证器和 ValidationSummary 中使用 ValidationGroup 属性。

编辑:另一种可能性可能是服务器验证码

args.IsValid = (!CampaignRegistration.IsMemberRegistered(args.Value));

如果CampaignRegistration.IsMemberRegistered(args.Value)返回假,“!” 使它成为真的,因此使它有效。我认为你应该摆脱“!” 如下:

args.IsValid = CampaignRegistration.IsMemberRegistered(args.Value);

更新:为了使 ValidationSummary 在消息框中显示您的自定义验证器消息,您需要拥有ClientValidationFunction代码。如果您只需要显示摘要而不显示弹出窗口,则不需要。

<asp:CustomValidator ID="cvMemberNum" runat="server" 
    CssClass="ValidationMessage" Display="Dynamic"
    ControlToValidate="txtMemberNum" ValidateEmptyText="false"
    OnServerValidate="cvMemberNum_Validate"
    ClientValidationFunction = "ClientValidate"  
    ErrorMessage="This membership number is already registered">*</asp:CustomValidator>
   //JavaScript Code.
   function ClientValidate(source, args)
   {         
      args.IsValid = false; //you need to add validation logic here
   }

更多:如果你不想做客户端验证,试试这个技巧来显示警报。对您的 CustomValidator ServerValidate 方法进行此更改:

protected void cvMemberNum_Validate(object source, ServerValidateEventArgs args)
{
    bool isValid = true;
    try
    {
        isValid  = (!CampaignRegistration.IsMemberRegistered(args.Value));
    }
    catch
    {
        isValid = false;
    }
    args.IsValid = isValid;

    if(!isValid)
    {
       if(!Page.IsClientScriptBlockRegistered("CustomValidation")) 
         Page.RegisterClientScriptBlock("CustomValidation", "<script>alert('This membership number is already registered');</script>"); 

    }

}
于 2009-05-01T15:00:04.100 回答
7

ShowMessageBox选项完全是客户端的,因此它只会评估您是否在CustomValidator上设置了ClientValidationFunction

您还可以通过注册发出警报的脚本来伪造它,因此当您从服务器验证返回时,它会提示错误消息。这可以在 ServerValidate 方法中注册(每个@Jose Basilio),或者您可以在 PreRender 事件期间调用以下方法来注册一个包含页面上所有无效验证器的弹出窗口:

    /// <summary>
    /// Registers a script to display error messages from server-side validation as the specified <see cref="UserControl"/> or <see cref="Page"/> loads from a postback.
    /// </summary>
    /// <remarks>
    /// Must be called in the PreRender if used to validate against the Text property of DNNTextEditor controls, otherwise Text will not be populated.
    /// Must set the ErrorMessage manually if using a resourcekey, otherwise the resourcekey will not have overridden the ErrorMessage property.
    /// </remarks>
    /// <param name="ctrl">The <see cref="UserControl"/> or <see cref="Page"/> which is being posted back.</param>
    /// <param name="validationGroup">The validation group against which to validate.</param>
    public static void RegisterServerValidationMessageScript(TemplateControl ctrl, string validationGroup)
    {
        if (ctrl != null && ctrl.Page.IsPostBack)
        {
            ctrl.Page.Validate(validationGroup);
            if (!ctrl.Page.IsValid)
            {
                StringBuilder errorMessage = new StringBuilder("<script language='javascript'>alert('");
                for (int i = 0; i < ctrl.Page.Validators.Count; i++)
                {
                    IValidator validator = ctrl.Page.Validators[i];
                    if (!validator.IsValid)
                    {
                        errorMessage.Append("- " + validator.ErrorMessage);
                        if (i < ctrl.Page.Validators.Count - 1)
                        {
                            errorMessage.Append(@"\r\n");
                        }
                    }
                }

                errorMessage.Append("');</script>");
                ctrl.Page.ClientScript.RegisterStartupScript(typeof(IValidator), "validationAlert", errorMessage.ToString(), false);
            }
        }
    }
于 2009-05-01T16:24:29.950 回答
5

我最近遇到了同样的问题。当 ServerValidate 声明验证失败时,ValidationSummary 未显示来自 CustomValidator 的 ErrorMessage。由于默认情况下(正如我的小逆向工程所示)验证摘要在回发时呈现客户端,我只是添加了一个脚本,用于检查文档加载/异步回发完成的所有验证器,并为失败的验证组触发验证摘要创建:

$(document).ready(function () {
    var displayAlert = function () {
        if (typeof Page_Validators == 'undefined') return;

        var groups = [];
        for (i = 0; i < Page_Validators.length; i++)
            if (!Page_Validators[i].isvalid) {
                if (!groups[Page_Validators[i].validationGroup]) {
                    ValidationSummaryOnSubmit(Page_Validators[i].validationGroup);
                    groups[Page_Validators[i].validationGroup] = true;
                }
            }
    };

    displayAlert();

    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(
                    function () {
                        displayAlert();
                    });
}
);

在我的场景中,我在父页面上嵌套了带有验证器、更新面板和验证摘要的用户控件。

更多细节在这里。

于 2010-09-06T14:32:18.890 回答
1

你应该写一个属性

ValidationGroup="ValidationSummary1"

在您的案例中的每个验证器上。

还要检查您的页面是否有

AutoEventWireup="true"
于 2009-05-01T15:12:20.903 回答
1

这对我有用:

<asp:CustomValidator runat="server" ID="cv" 
ClientValidationFunction="ValidateFunction"
ErrorMessage="Default error
message">*</asp:CustomValidator>

<script type="text/javascript">
function ValidateFunction(sender, args) 
{

var msg ='';
var formValid = true;

[various checks setting msg and formValid]

if (msg.length > 0) { sender.errormessage = msg; }
args.IsValid = formValid;

}
</script>
于 2010-08-03T09:47:46.747 回答
1

当 javascript 被禁用并且ValidationSummary不显示errorMessage. CustomValidator这是必需的,因为如上所述的注入脚本或警报将不起作用。

添加一个新的 Validator 控件,我们将其命名为CustomValidatorProxy,将其ControlToValidate属性设置为窗体上的任何一个控件,然后EnableClientScript=false.

ServerValidate事件处理程序中执行您的自定义验证,如果验证失败,则将 and 的属性设置为IsValidfalse并类似地设置这两个属性。 CustomValidatorCustomValidatorProxyErrorMessage

如果通过了验证,请ServerValidate确保将 IsValid 属性CustomValidatorProxy设置为 true。

如果在PageCustomValidatorProxy之前,ServerValidate 处理程序将覆盖在验证值后返回的属性值,并且您的from your将显示在.CustomValidatorValidatorCollectionIsValidCustomValidatorProxyControlToValidateErrorMessageCustomValidatorValidationSummary

于 2010-10-26T15:28:20.323 回答
1

bduke 的 RegisterServerValidationMessageScript 是在“伪造”,但事实并非如此。它确实解决了问题。每个 Utility 命名空间都需要这个函数。

于 2011-04-11T16:08:05.370 回答