asp.net 自定义验证器未针对文本框触发

发布于 2024-10-19 15:34:18 字数 942 浏览 6 评论 0原文

我有一个必需的字段验证器和自定义验证器来验证文本框。所需的字段验证器完美触发。我无法让自定义验证器正确触发?

<asp:TextBox ID="txtPRI" runat="server" Width="295" /><br />

<asp:RequiredFieldValidator display="Dynamic" CssClass="leftAlign" SetFocusOnError="true"  runat="server" controltovalidate="txtPRI" errormessage="Please enter your PRI" />

 <asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtPRI" onservervalidate="cusCustom_ServerValidate" Enabled="true" ValidateEmptyText="true" display="Dynamic" CssClass="leftAlign" SetFocusOnError="true"  errormessage="The text must be exactly 8 characters long!" />

代码隐藏

protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
    {
        Response.Write("firing - test");
        Response.End();


        if (e.Value.Length == 8)
            e.IsValid = true;
        else
            e.IsValid = false;
    }

I have both a required field validator and custom validator for validating a texbox. The required field validator fires perfectly. I'm not able to get the custom validator to fire properly?

<asp:TextBox ID="txtPRI" runat="server" Width="295" /><br />

<asp:RequiredFieldValidator display="Dynamic" CssClass="leftAlign" SetFocusOnError="true"  runat="server" controltovalidate="txtPRI" errormessage="Please enter your PRI" />

 <asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtPRI" onservervalidate="cusCustom_ServerValidate" Enabled="true" ValidateEmptyText="true" display="Dynamic" CssClass="leftAlign" SetFocusOnError="true"  errormessage="The text must be exactly 8 characters long!" />

code behind

protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
    {
        Response.Write("firing - test");
        Response.End();


        if (e.Value.Length == 8)
            e.IsValid = true;
        else
            e.IsValid = false;
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

征﹌骨岁月お 2024-10-26 15:34:18

检查您的 CustomValidator 属性 ValidateEmptyText 设置为 true,以便验证空文本。那么您将不再需要 RequiredFieldValidator

编辑:我获取了您的代码并将其复制并粘贴到一个空项目中,它按预期工作。一定有一些我们不知道的您未发布或发布错误的内容。还有其他什么会影响触发验证的按钮或验证控件本身吗?

编辑:这是确切的代码(位于内容页面中):

aspx页面:

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:TextBox ID="txtPRI" runat="server" Width="295" /><br />
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" display="Dynamic" CssClass="leftAlign" SetFocusOnError="true"  runat="server" controltovalidate="txtPRI" errormessage="Please enter your PRI" />  
    <asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtPRI" onservervalidate="cusCustom_ServerValidate" Enabled="true" ValidateEmptyText="true" display="Dynamic" CssClass="leftAlign" SetFocusOnError="true"  errormessage="The text must be exactly 8 characters long!" /> 
</asp:Content>

.cs页面(空Page_Load):

protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{ 
    // put a break point here and it stops on it
    if (e.Value.Length == 8)
        e.IsValid = true;
    else
        e.IsValid = false;
} 

Check that you have the your CustomValidator property ValidateEmptyText set to true so that empty text will be validated. Then you will not need the RequiredFieldValidator anymore.

EDIT: I took your code and copy and pasted it into an empty project and it works as expected. There must be something you have not posted, or is posting incorrectly, that we are not aware of. Is there anything else that affects the button that is triggering the validation or the validation controls themselves?

EDIT: Here is the exact code (it's in a content page):

aspx page:

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:TextBox ID="txtPRI" runat="server" Width="295" /><br />
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" display="Dynamic" CssClass="leftAlign" SetFocusOnError="true"  runat="server" controltovalidate="txtPRI" errormessage="Please enter your PRI" />  
    <asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtPRI" onservervalidate="cusCustom_ServerValidate" Enabled="true" ValidateEmptyText="true" display="Dynamic" CssClass="leftAlign" SetFocusOnError="true"  errormessage="The text must be exactly 8 characters long!" /> 
</asp:Content>

.cs page (empty Page_Load):

protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{ 
    // put a break point here and it stops on it
    if (e.Value.Length == 8)
        e.IsValid = true;
    else
        e.IsValid = false;
} 
つ低調成傷 2024-10-26 15:34:18

好吧......非常老的问题,还没有被接受的答案,我刚刚遇到了同样的问题。

因此,我将把这个问题抛给可能遇到此问题并需要答案的其他人...

如果您正在执行常规验证以及自定义服务器验证,则只有在所有其他验证都已完成的情况下,自定义服务器验证才会触发至少干净地回来,这对我来说就是这样。

Ok... really old question with no accepted answer yet, and I just ran into the same issue.

So I'm going to throw this out there for anyone else who might have this problem and needs an answer...

If your're doing regular validations, along with custom server validations, the custom server validation will only fire if all other validations come back clean, at least, that's the way it's worked for me.

染火枫林 2024-10-26 15:34:18

请记住在 CustomValidator 上设置此属性...

ValidateEmptyText="True"

Remember to set this property on the CustomValidator...

ValidateEmptyText="True"
游魂 2024-10-26 15:34:18

除了上面的建议之外,我发现使用较新版本的 .Net 框架,您必须在服务器上显式触发 validate() 方法才能获取自定义验证器例程

    // validate page before allowing import to go through
    Page.Validate();
    if (!Page.IsValid)
        return;

In addition to the suggestions above, I've found that with newer versions of the .Net framework you must explicitly fire the validate() method at the server to get the custom validator routine

    // validate page before allowing import to go through
    Page.Validate();
    if (!Page.IsValid)
        return;
站稳脚跟 2024-10-26 15:34:18

我也有这个问题。是的,所有其他验证器都必须在 CustomValidator 触发之前通过。

但是,如果这对您不起作用,那么您可能需要使用 Page.Validate() 强制验证您的特定验证组

我就是这样做的,并且我仍然设法保留了我的 RequiredFieldValidator 并且不需要 ValidateEmptyText="true"

在文本框中添加陷阱以强制验证。

<asp:TextBox ID="txtLeft" runat="server" Width="110px" TextMode="SingleLine" style="text-align:center" OnTextChanged="TextBoxChanged_DateTimeTest" AutoPostBack="True" ValidationGroup="vg2"></asp:TextBox>

请注意,我正在使用特定的 ValidationGroup“vg2”,因为我还有其他不想验证的区域。

另外,我想验证日期&时间!

你还需要两件事。 TextBoxChanged_DateTimeTest 方法...

protected void TextBoxChanged_DateTimeTest(object sender, EventArgs e)
    {
        Page.Validate("vg2");
        if (!Page.IsValid)
        {
            TextBox tb1 = (TextBox)sender;
            IFormatProvider culture = new CultureInfo("en-AU", true);

            //if page is not valid, then validate the date here and default it to today's date & time, 
            String[] formats = { "dd MM yyyy HH:mm", "dd/MM/yyyy HH:mm", "dd-MM-yyyy HH:mm" };
            DateTime dt1;
            DateTime.TryParseExact(tb1.Text, formats, culture, DateTimeStyles.AdjustToUniversal, out dt1);
            if (dt1.ToShortDateString() != "1/01/0001")
                tb1.Text = dt1.ToShortDateString() + " " + dt1.ToShortTimeString();
            else
                tb1.Text = DateTime.Today.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
        }
    }

并且您还需要对 CustomValidator 进行服务器端验证。就我而言,文本框必须接受日期和日期。时间!

这是标记...

<asp:CustomValidator ID="CustomValidator3" runat="server" ControlToValidate="txtLeft" ErrorMessage="Invalid date & time format (dd/MM/yyyy HH:mm)" 
                                    SetFocusOnError="true" ValidationGroup="vg2" OnServerValidate="CustomValidator_DateTime"></asp:CustomValidator>

这是背后的代码...

protected void TextBoxChanged_DateTimeTest(object sender, EventArgs e)
{
    Page.Validate("vg2");
    if (!Page.IsValid)
    {
        TextBox tb1 = (TextBox)sender;
        IFormatProvider culture = new CultureInfo("en-AU", true);

        //if page is not valid, then validate the date here and default it to today's date & time, 
        String[] formats = { "dd MM yyyy HH:mm", "dd/MM/yyyy HH:mm", "dd-MM-yyyy HH:mm" };
        DateTime dt1;
        DateTime.TryParseExact(tb1.Text, formats, culture, DateTimeStyles.AdjustToUniversal, out dt1);
        if (dt1.ToShortDateString() != "1/01/0001")
            tb1.Text = dt1.ToShortDateString() + " " + dt1.ToShortTimeString();
        else
            tb1.Text = DateTime.Today.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
    }
}

祝你好运!

I had this problem too. Yes all other validators have to pass before the CustomValidator fires.

However, if that does not work for you, then you may need to force a validate of your specific validation group using the Page.Validate().

This is how I did it, and I still managed to keep my RequiredFieldValidator and no need for ValidateEmptyText="true".

Add a trap in the textbox to force a validate.

<asp:TextBox ID="txtLeft" runat="server" Width="110px" TextMode="SingleLine" style="text-align:center" OnTextChanged="TextBoxChanged_DateTimeTest" AutoPostBack="True" ValidationGroup="vg2"></asp:TextBox>

Note that I am using a specific ValidationGroup "vg2", as I have other areas that I don't want to validate.

Also, I want to validate date & time!

You need two more things. The TextBoxChanged_DateTimeTest method ...

protected void TextBoxChanged_DateTimeTest(object sender, EventArgs e)
    {
        Page.Validate("vg2");
        if (!Page.IsValid)
        {
            TextBox tb1 = (TextBox)sender;
            IFormatProvider culture = new CultureInfo("en-AU", true);

            //if page is not valid, then validate the date here and default it to today's date & time, 
            String[] formats = { "dd MM yyyy HH:mm", "dd/MM/yyyy HH:mm", "dd-MM-yyyy HH:mm" };
            DateTime dt1;
            DateTime.TryParseExact(tb1.Text, formats, culture, DateTimeStyles.AdjustToUniversal, out dt1);
            if (dt1.ToShortDateString() != "1/01/0001")
                tb1.Text = dt1.ToShortDateString() + " " + dt1.ToShortTimeString();
            else
                tb1.Text = DateTime.Today.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
        }
    }

And you also need the server side validate for the CustomValidator. In my case the TextBox has to accept a date & time!

So here's the markup...

<asp:CustomValidator ID="CustomValidator3" runat="server" ControlToValidate="txtLeft" ErrorMessage="Invalid date & time format (dd/MM/yyyy HH:mm)" 
                                    SetFocusOnError="true" ValidationGroup="vg2" OnServerValidate="CustomValidator_DateTime"></asp:CustomValidator>

And here's the code behind ...

protected void TextBoxChanged_DateTimeTest(object sender, EventArgs e)
{
    Page.Validate("vg2");
    if (!Page.IsValid)
    {
        TextBox tb1 = (TextBox)sender;
        IFormatProvider culture = new CultureInfo("en-AU", true);

        //if page is not valid, then validate the date here and default it to today's date & time, 
        String[] formats = { "dd MM yyyy HH:mm", "dd/MM/yyyy HH:mm", "dd-MM-yyyy HH:mm" };
        DateTime dt1;
        DateTime.TryParseExact(tb1.Text, formats, culture, DateTimeStyles.AdjustToUniversal, out dt1);
        if (dt1.ToShortDateString() != "1/01/0001")
            tb1.Text = dt1.ToShortDateString() + " " + dt1.ToShortTimeString();
        else
            tb1.Text = DateTime.Today.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
    }
}

Good luck!

银河中√捞星星 2024-10-26 15:34:18

问题是您正在调用 Response.End() 可有效停止页面的所有执行。因此,if/else 块根本没有运行。在调试时注释掉该行或跳过它,验证器将按预期触发。

我建议您使用调试器,而不是以这种方式编写响应,或者如果您选择使用它,请注意 Response.End() 的后果。

The problem is that you're calling Response.End() which effectively stops all execution of the page. Thus, the if/else block isn't being run at all. Comment that line out or skip over it while debugging and the validator will fire as expected.

I suggest you use a debugger instead of writing responses out in this fashion or be aware of the consequences of Response.End() if you choose to use it.

悲欢浪云 2024-10-26 15:34:18

据我记得,如果您的文本框为空,自定义验证器将不会触发。

As far as I remember, custom validator will not fire if your textbox is empty.

离旧人 2024-10-26 15:34:18

如果代码中有多个部分并且每个部分都有一些验证器,请为每个部分创建 validateGroup

if you have multiple part in your code and each part has some validator, create validateGroup for each part

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文