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; 
     } 
    } 
+0

你的问题很混乱;你能否在自定义验证器中使用该脚本进行验证? – techspider

+0

它不验证 – jdag

回答

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事件处理程序在修改后的字段失去焦点时被调用。没有它,只有在回发被触发时才进行验证。

0

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