如何对多个控件使用自定义验证器?

how to use custom validator for multiple controls?

我有日期字段,我想验证是否选择了两个日期或 none。 我添加了以下 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;
        }
    }

如果日期字段呈现为文本框(我不熟悉 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 事件处理程序。没有它,只有在触发回发时才会进行验证。

您的 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;
}