我有日期字段,我想验证两个日期是否都被选中。 我添加了以下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 :(得分:1)
如果日期字段呈现为TextBoxes(我不熟悉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
事件处理程序。没有它,只有在触发回发时才会进行验证。
答案 1 :(得分: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"> </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;
}