如果验证失败,则不会触发带有ClientValidationFunction的ASP.NET CustomValidator

问题描述

|| 我正在使用customvalidator验证日期,但是效果不佳,有人可以告诉原因 这是我的.aspx
    <script type=\"text/javascript\">

function monthDiff(d1,d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth() + 1;
    months += d2.getMonth();
    return months;
}

function difference(d1,d2){

var hiredate,dob;
var diff=18*12;
hiredate=document.getElementById(d1).value;
dob=document.getElementById(d2).value;
var months=monthDiff(hiredate,dob);
if(diff<=months)
{
return true;
//true
}
else
{
return false;
//false
}
}

function validatehiredate(value,arg) {
                arg.IsValid = (difference(\'ctl00_ContentPlaceHolder1_txtHiredate\',\'ctl00_ContentPlaceHolder1_txtDateofBirth\'));
            }
</script>

 <asp:TextBox id=\"txtHiredate\" runat=\"server\" />
 <asp:TextBox id=\"txtDateofBirth\" runat=\"server\" />
 <asp:CustomValidator ID=\"CustomValidator1\" runat=\"server\" ClientValidationFunction=\"validatehiredate\" ControlTovalidate=\"txtDateofBirth\" ValidationGroup=\"personal\" display=\"Dynamic\" ValidateEmptyText=\"True\">can not hire guy less than 18 yrs</asp:CustomValidator>
谁能告诉我这是怎么回事     

解决方法

        将您的monthDiff函数更改为以下内容:
 function monthDiff(d1,d2) {
        var months;
        var date1 = new Date(d1);
        var date2 = new Date(d2);

        months = (date2.getFullYear() - date1.getFullYear()) * 12;
        months -= date1.getMonth() + 1;
        months += date2.getMonth(); return months;
       }
您不能在日期对象以外的任何其他对象上使用date2ѭ或
getMonth
。 我将假设您的浏览器抛出了JavaScript错误,只是没有弹出 编辑
        function getDays(d1,d2) {
            var months;
            var date1 = new Date(d1);
            var date2 = new Date(d2);
            return (date2 - date1) / (1000 * 60 * 60 * 24);
            return months;
        }

        //function getLeapYear

        function difference(d1,d2) 
        {
            var hiredate,dob; var diff = 18 * 12;
            hiredate = document.getElementById(d1).value;
            dob = document.getElementById(d2).value;
            var Age = getDays(hiredate,dob);
            var compareVal = 365 * 18; //getCompareVal(hiredate,dob);

            if (Age >= compareVal) {
                return true;
                //true
            } else {
                return false; //false
            }
        }