0

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

2 回答 2

3

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

于 2016-04-26T22:25:47.007 回答
1

您的 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;
}
于 2016-04-27T02:23:05.983 回答