简体   繁体   English

ASP.NET自定义验证器未触发

[英]ASP.NET Custom Validator not firing

Here's the deal: I built a custom validator that should only fire if there is input in the text box. 达成协议:我建立了一个自定义验证器,该验证器仅在文本框中有输入时才触发。 When it fires, it should test to see if the text in the box is an integer, and it will reject it if not. 触发时,它应该进行测试以查看框中的文本是否为整数,否则将拒绝它。 It won't fire, though, and I'm trying to figure out why. 不过,它不会触发,我正试图找出原因。

I put this void in the body of the partial c# class: 我将这个空白放在部分c#类的主体中:

    protected void intValidate_Validate(object sender, ServerValidateEventArgs arg)
    {
        int num;
        bool isNum = int.TryParse(arg.ToString(), out num);

        if(arg.Value.Length>0){
            if (isNum)
             {
                arg.IsValid = true;
             }
             else
             {
                arg.IsValid = false;
             }
        }
        else{
            arg.IsValid=true;
        }
    }

The code for the validator is as follows: 验证器的代码如下:

 <div class="adult">
            <label>Adults ($10)</label>
            <asp:TextBox runat="server" ID="wAdultLunch" class="adultLunch" MaxLength="2" />
            <asp:CustomValidator ID="intValidate" ControlToValidate="wAdultLunch" ErrorMessage="Invalid number" OnServerValidate="intValidate_Validate" Display="Static" runat="server" EnableClientScript="False" ValidateEmptyText="True"></asp:CustomValidator>
 </div>

Insight would be appreciated! 有识之士将不胜感激!

EDIT: I attached the postback code below 编辑:我附上下面的回发代码

<asp:Button ID="wSubmit" runat="server" Text="Submit" OnClientClick="return validateForm();" causesvalidation="true"/>

You are doing the parse on the wrong thing. 您正在对错误的内容进行解析。 arg.ToString() will give you the string of "System.Web.UI.WebControls.ServerValidateEventArgs" , when you actually want to the arg.Value (which is already a string) 实际需要arg.Value时, arg.ToString()将为您提供字符串"System.Web.UI.WebControls.ServerValidateEventArgs" (已经是字符串)

So, instead of... 所以,而不是...

bool isNum = int.TryParse(arg.ToString(), out num);

Change it to (note the .Value )... 更改为(注意.Value )...

bool isNum = int.TryParse(arg.Value, out num);

Although it is a lot more complex than it actually needs to be. 尽管它比实际需要复杂得多。 The whole thing could be rewritten a lot more comprehensively like this... 整个事情可以像这样更全面地重写...

protected void intValidate_Validate(object sender, ServerValidateEventArgs arg)
{
    int num;
    arg.IsValid = int.TryParse(are.Value, out num);
}

This is because TryParse will return a true if the conversion was successful, and false otherwise. 这是因为TryParse如果转换成功将返回true,否则返回false。

And as a final thought, all this could be achieved using the <asp:RequiredFieldValidator ...> , <asp:CompareValidator Operator="DataTypeCheck" Type="Integer" ...> and <asp:RangeValidator ...> validator controls. 最后,可以使用<asp:RequiredFieldValidator ...><asp:CompareValidator Operator="DataTypeCheck" Type="Integer" ...><asp:RangeValidator ...>验证程序来实现所有这些<asp:CompareValidator Operator="DataTypeCheck" Type="Integer" ...>控制。


UPDATE UPDATE

As the OP points out, he doesn't want the error when when the textbox is empty, so instead try this... 正如OP指出的那样,当文本框为空时,他不希望出现此错误,因此请尝试...

protected void intValidate_Validate(object sender, ServerValidateEventArgs arg)
{
    if (args.Value.Length > 0)
    {
        int num;
        arg.IsValid = int.TryParse(are.Value, out num);
    }
    else
    {
        arg.IsValid = true;
    }
}

And has already been pointed out by @HansKesting... this will only ever be called if all client-side validation is passed. @HansKesting已经指出了这一点……只有通过所有客户端验证后,才能调用此方法。 As soon as client-side validation fails, the submission of the form back to the server is also cancelled. 一旦客户端验证失败,则将表单提交回服务器的操作也将被取消。

I don't know if it's related, but I had an issue with a custom validator not firing. 我不知道它是否相关,但是我遇到了自定义验证器无法触发的问题。 I had it validating a dropdownlist, which had a default value of an empty string. 我验证了一个dropdownlist,它的默认值为空字符串。 I had to set 我必须设定

ValidateEmptyString="true" 

and then it started working just fine. 然后它开始正常工作。

You could also call the Validate() function and read the IsValid property from the custom validator control. 您还可以调用Validate()函数并从自定义验证程序控件中读取IsValid属性。 However, the Page's validation function should work just fine, and shouldn't require such a call. 但是,Page的验证功能应该可以正常工作,并且不需要这样的调用。

I suppose you have a server side event to execute if the validation passes. 我想如果验证通过,您有一个服务器端事件要执行。 for ex: a button click event. 例如:按钮单击事件。 In that if you check Page.IsValid then it will be false if the validation passes then Page.IsValid will be true. 在这种情况下,如果您检查Page.IsValid,那么如果验证通过,它将为false,则Page.IsValid将为true。 You need to use Page.IsValid to check whether the validation passed or not. 您需要使用Page.IsValid来检查验证是否通过。

On the front-end try setting the CausesValidation attribute to true as shown below. 在前端,尝试将CausesValidation属性设置为true,如下所示。 See if that helps. 看看是否有帮助。

<asp:Button ID="btnSubmit" Text="Submit" CausesValidation="true" runat="server" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM