【问题标题】:how to use custom validator for multiple controls?如何为多个控件使用自定义验证器?
【发布时间】:2016-04-26 19:41:43
【问题描述】:

我有日期字段,我想验证是否选择了两个日期或都没有。 我添加了以下 customValidator

<asp:CustomValidator ID="CustomValidator3" runat="server" ErrorMessage="CustomValidator" Text="You must select both or no dates" ClientValidationFunction="dateValidate"  ValidateEmptyText="false" Font-Size="Small" Font-Bold="True" ForeColor="Red" SetFocusOnError="True"></asp:CustomValidator>

但如果我不添加 customvalidator,它就不起作用。我的客户端功能如下。否则,当我直接在日期字段中进行验证但我尝试使用 customvalidator 来实现它时,此方法可以正常工作。

    function dateValidate(sender, args) {

        var From = document.getElementById('dataContentplaceholder_wdpFrom').title;

        var To = document.getElementById('dataContentplaceholder_wdpTo').title;
        if (From.toString.length == 0 && To.toString.length >=1 || To.toString.length == 0 && From.toString.length >=1) {

            args.IsValid = false;
        }
        else {

            args.IsValid = true;
        }
    }

【问题讨论】:

  • 您的问题令人困惑;您是否能够在自定义验证器中使用该脚本进行验证?
  • 它不验证

标签: javascript asp.net validation infragistics asp.net-validators


【解决方案1】:

如果日期字段呈现为文本框(我不熟悉 Infragistics),您可以使用类似于此的标记:

<asp:TextBox ID="txtBox1" runat="server" onchange="ValidateTexts();" ... />
<asp:TextBox ID="txtBox2" runat="server" onchange="ValidateTexts();" ... />
<asp:CustomValidator ID="customValidator1" runat="server" Text="You must select both or no dates" ForeColor="Red" ClientValidationFunction="txtValidate"  ValidateEmptyText="true" ... />

使用以下客户端代码:

function ValidateTexts() {
    ValidatorValidate(document.getElementById('<%= customValidator1.ClientID %>'));
}

function txtValidate(sender, args) {
    var from = document.getElementById('<%= txtBox1.ClientID %>').value;
    var to = document.getElementById('<%= txtBox2.ClientID %>').value;
    args.IsValid = (from.length == 0 && to.length == 0) || (to.length > 0 && from.length > 0);
}

当修改的字段失去焦点时调用onchange 事件处理程序。没有它,只有在触发回发时才会进行验证。

【讨论】:

    【解决方案2】:

    您的 customValidator 应该被某个提交按钮触发。

    <asp:ValidationSummary ID="vs" runat="server" />
    <asp:TextBox ID="txtBox1" runat="server" ... />
    <asp:TextBox ID="txtBox2" runat="server" ... />
    <asp:CustomValidator ID="cVal" runat="server" ErrorMessage="You must select both or no dates" ClientValidationFunction="valDates">&nbsp;</asp:CustomValudator>
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
    
    function valDates(s, e){
        var txt1 = document.getElementById(s.id.replace('cVal', 'txtBox1'));
        var txt2 = document.getElementById(s.id.replace('cVal', 'txtBox2'));
        if(!(txt1.value && txt2.value) && !(!txt1.value && !txt2.value))
            e.IsValid = false;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      相关资源
      最近更新 更多