简体   繁体   English

自定义验证客户端忽略无效状态

[英]Custom validation client side ignores invalid state

I want to make custom validator which checks if objects of given name already exists in DB. 我想做一个定制的验证器来检查给定名称的对象是否已经存在于数据库中。 WS works fine and arg.IsValid is set false BUT when I uncomment Page_ClientValidate(); WS正常工作,并且arg.IsValid当我取消注释Page_ClientValidate();时,将arg.IsValid设置为false,但是Page_ClientValidate(); function goes into infinite loop ( I guess it runs all validators functions that why) nevertheless it return false but when page is submited, validator starts to return true O.o'. 函数进入无限循环(我猜它运行了为什么所有的验证器函数),但是它返回false,但是当提交页面时,验证器开始返回true O.o'。

How to abort postback if txtname is not valid? 如果txtname无效,如何中止回txtname I suspect it because when I press button smsCodeValidator is actually run but aborted due to postback 我怀疑这是因为当我按下按钮smsCodeValidator实际上运行但由于回发而中止

<asp:CustomValidator 
  ID="cvtxtSMSCode" 
  runat="server" Display="Dynamic" 
  ControlToValidate="txtName" 
  EnableClientScript="true"
  ClientValidationFunction="$U.nameValidator" 
  ForeColor="Red" 
  ErrorMessage="already exists" 
  ValidationGroup="vgName">
</asp:CustomValidator>

nameValidator: function (source, arg) {
    $.ajax({
        type: "POST",
        url: "/../../../../WS/Utility.asmx/NameValidator",
        data: JSON.stringify({ "toTest": arg.Value }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            if (result.d == true) {
                arg.IsValid = true;
                $(source).hide();
                return;
            }
            else {
                $(source).show();
                arg.IsValid = false;
                alert(arg.IsValid);
                //Page_ClientValidate();
                return;
            }
        }
    });
},

<asp:Button ID="btnSave" ValidationGroup="vgName" 
runat="server" 
OnClick="btnSaveChanges_Click"
Text="Save" />

I believe you're going into the infinite loop because you're trying to validate the page when you know it's in an invalid state. 我相信您会进入无限循环,因为您在知道页面处于无效状态时正尝试验证该页面。

Page_ClientValidate() will call each of the validators in turn to make sure they have fired and when it gets to your custom validator you are kicking it off again which will cause the recursion you are seeing. Page_ClientValidate()将依次调用每个验证器,以确保它们已触发,当它到达您的自定义验证器时,您将再次启动它,这将导致您看到的递归。 A better option would be to check the value of Page_IsValid instead which is kept up to date by the other validators as well. 更好的选择是检查Page_IsValid的值,而其他验证程序也将其保持最新。

Finally, don't forget that if the text box is empty the validator won't be called, you need to have a required field validator on there as well. 最后,不要忘记,如果文本框为空,则不会调用验证器,您还需要在该字段上具有必需的字段验证器。

More details can be found on the MSDN article: ASP.Net Validation In Depth . 可以在MSDN文章“ ASP.Net深度验证”中找到更多详细信息。

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

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