启用/禁用 asp:validators 使用 jquery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9704039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:10:39  来源:igfitidea点击:

Enable/Disable asp:validators using jquery

jqueryasp.netwizardrequiredfieldvalidator

提问by Thomas

I am working with a wizard, where the user can sign up. There is a asp:RadioButtonList with two options, and some of the input fields in the wizard changes when the radiobutton changes. On each field there is some asp:Validators (asp:RequiredFieldValidator for example). The problem is, that when the user submits the page, the validator for the hidden textbox is still popping up.

我正在使用一个向导,用户可以在其中注册。有一个 asp:RadioButtonList 有两个选项,当单选按钮改变时,向导中的一些输入字段也会改变。在每个字段上都有一些 asp:Validators(例如 asp:RequiredFieldValidator)。问题是,当用户提交页面时,隐藏文本框的验证器仍在弹出。

First, here is the div tags which changes the shown textboxes and the RadioButtonList

首先,这里是改变显示的文本框和 RadioButtonList 的 div 标签

<div id="divTxt1">
  <asp:TextBox runat="server" CssClass="text" ID="txtNumber"
       type="number"/>
  <asp:RequiredFieldValidator ID="RequiredFieldValidator1" 
       runat="server" ControlToValidate="txtNumber" EnableClientScript="true" ErrorMessage="Error" ToolTip="Error">*
   </asp:RequiredFieldValidator>
</div>
<div id="divTxt2">
  <asp:TextBox runat="server" CssClass="text" ID="txtNumber2"
       type="number"/>
  <asp:RequiredFieldValidator ID="RequiredFieldValidator2" 
       runat="server" ControlToValidate="txtNumber2" EnableClientScript="true" ErrorMessage="Error2" ToolTip="Error2">*
   </asp:RequiredFieldValidator>
</div>
<div id="radio">
<asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatDirection="Horizontal">
   <asp:ListItem Value="1" Selected="True">Privat</asp:ListItem>
   <asp:ListItem Value="2">Offentlig</asp:ListItem>
   </asp:RadioButtonList>
</div>

I have tried to solve it using JQuery like the following, which I have read should do the trick, but unfortunately it doesn't:

我曾尝试使用 JQuery 解决它,如下所示,我读过它应该可以解决问题,但不幸的是它没有:

$(document).ready(function () {

    $('#<%= WizardStep1.ContentTemplateContainer.FindControl("RadioButtonList1").ClientID %> input').change(function () {
        if ($(this).val() == "1") {
            $('#txtNumber').toggle('fast');
            $('#txtNumber2').toggle('fast');     
            ValidatorEnable($('#<%=WizardStep1.ContentTemplateContainer.FindControl("RequiredFieldValidator1").ClientID %>')[0], false);
            ValidatorEnable($('#<%=WizardStep1.ContentTemplateContainer.FindControl("RequiredFieldValidator2").ClientID %>')[0], true);
        }

        if ($(this).val() == "2") {
            $('#txtNumber').toggle('fast');
            $('#txtNumber2').toggle('fast');
            ValidatorEnable($('#<%=WizardStep1.ContentTemplateContainer.FindControl("RequiredFieldValidator2").ClientID %>')[0], false);
            ValidatorEnable($('#<%=WizardStep1.ContentTemplateContainer.FindControl("RequiredFieldValidator1").ClientID %>')[0], true);
        }
    });
});

So, any ideas what's wrong?

那么,有什么想法有什么问题吗?

采纳答案by RemarkLima

The client side API for validators is here.

验证器的客户端 API 在这里

Something you may be able to adapt to your needs (this will disable all the validators via client script):

您可能能够适应您的需求(这将通过客户端脚本禁用所有验证器):

if (Page_Validators) {
    PageValidators.forEach(function(pageValidator) {
        if (pageValidator == null) {return;}
        vldGrp = pageValidator.validationGroup;
        ValidatorEnable(pageValidator, false);
    });
};

So you could add a ifblock to check the validator name, or more so the .controlToValidatewhich returns the target ID of the validator - then disable it:

所以你可以添加一个if块来检查验证器名称,或者更多的.controlToValidate是返回验证器的目标 ID - 然后禁用它:

if (Page_Validators) {
    PageValidators.forEach(function(pageValidator) {
        if (pageValidator == null) {return;}
        if (pageValidator.controltovaliddate != "<%= txtNumber2.ClientID %>") {
            return;
        }
        ValidatorEnable(pageValidator, false);
    });
};


You should also probably add a break in the loop if it's right one, if you don't need to check any further validators. You can use .someinstead of .forEachto break early:

如果您不需要检查任何进一步的验证器,您也应该在循环中添加一个中断(如果它是正确的)。您可以使用.some而不是.forEach提前休息:

if (Page_Validators) {
    PageValidators.some(function(pageValidator) {
        if (pageValidator == null) {return false;}
        if (pageValidator.controltovaliddate != "<%= txtNumber2.ClientID %>") {
            return false;
        }
        ValidatorEnable(pageValidator, false);
        return true;
    });
};


You can encapsulate this into a function:

你可以把它封装成一个函数:

var validatorState = function(element, isEnabled) {
    if (Page_Validators) {
        PageValidators.some(function(pageValidator) {
            if (pageValidator == null) {return false;}
            if (pageValidator.controltovaliddate != "<%= txtNumber2.ClientID %>") {
                return false;
            }
            ValidatorEnable(pageValidator, false);
            return true;
        });
    };
};

and use:

并使用:

validatorState('txtCancellationReson', true);

or

或者

validatorState($('#txtCancellationReson').attr('id'), true);

回答by Ads

I found a better option was to use simply:

我发现一个更好的选择是简单地使用:

document.getElementById("<%=myValidator.ClientID %>").enabled = true;

The ValidatorEnabled option as suggested above automatically calls the validation of the linked control and in my case shows the error message "please enter a value for seller name" which wasn't necessary or desired..

上面建议的 ValidatorEnabled 选项会自动调用链接控件的验证,在我的情况下显示错误消息“请输入卖家名称的值”,这不是必需的或不需要的。

Using the ".enabled = true" option doesn't.

使用“.enabled = true”选项不会。

回答by waycell

use CustomValidator control for "RadioButtonList1" and separate controls visibilty logic to another javascript function.

将 CustomValidator 控件用于“RadioButtonList1”,并将控件可见性逻辑与另一个 javascript 函数分开。

<div id="divTxt1">
    <asp:TextBox runat="server" CssClass="text" ID="txtNumber" type="number"/>
</div>
<div id="divTxt2">
<asp:TextBox runat="server" CssClass="text" ID="txtNumber2"
type="number"/>
</div>
<div id="radio">
    <asp:RadioButtonList ID="RadioButtonList1" runat="server"     RepeatDirection="Horizontal"      onchange:"javascript:toogleTexxBoxesVisibility(this);">
   <asp:ListItem Value="1" Selected="True">Privat</asp:ListItem>
   <asp:ListItem Value="2">Offentlig</asp:ListItem>
   </asp:RadioButtonList>
<asp:CustomValidator ID="CustomValidator1" runat="server"     ClientValidationFunction="clientSideValidationFunction" ControlToValidate="RadioButtonList1" OnServerValidate="CustomValidator1_ServerValidate" Text="Validation Error Message">asp:CustomValidator>

<script type="text/javascript">
function clientSideValidationFunction(source,arguments)
    var inputvalue = arguments.Value; //RadioButtonList1's value

   if (inputvalue == "1" && $('#txtNumber').val() == '') {
        arguments.IsValid = false;
   }
   else if (inputvalue == "2" && $('#txtNumber2').val() == '') {
        arguments.IsValid = false;
   }
   else {
        arguments.IsValid = true;
   }
};

function toogleTexxBoxesVisibility(radiobutton)
{
   if(radiobutton.val =='1')
   {
      $('#txtNumber').show('fast');
      $('#txtNumber2').hide('fast'); 
   }
  else if(radiobutton.val =='2')
  {
       $('#txtNumber').hide('fast');
       $('#txtNumber2').show('fast'); 
  }
}
</script>
</div>