如何防止CustomValidator做PostBack

时间:2016-12-17 20:42:21

标签: javascript asp.net validation

我一直在尝试对日期字段进行验证检查,但它一直在做回帖而不能正常工作.. 这是HTML:

<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="error"
Display="Dynamic" SetFocusOnError="True"
ClientValidationFunction="CheckDate"
ControlToValidate="txtDate">
</asp:CustomValidator>

和js中的函数:

function CheckDate(source, args)
    {           
        var inputDate = document.getElementById("<%=txtDate.ClientID%>");
        args.IsValid = false;

        var parts = inputDate.value.split("/");
        var day = parseInt(parts[0], 10);
        var month = parseInt(parts[1], 10);
        var year = parseInt(parts[2], 10);

        var d = new Date();
        var currentYear = d.getFullYear();
        if (year < currentYear - 50 || year > currentYear || month == 0 || month > 12)
            args.IsValid = false;

        var monthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        if (year % 4 == 0)
            monthLength[1] = 29;

        if (day > 0 && day <= monthDays[month - 1])
        {
            args.IsValid = true;                
        }

        return args.IsValid;
    } 

但没有成功..我如何防止它发生?

1 个答案:

答案 0 :(得分:0)

尝试添加ValidateEmptyText="true"。并改变返回结果的方式。

<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="error"
    Display="Dynamic" SetFocusOnError="True"
    ClientValidationFunction="CheckDate"
    ControlToValidate="txtDate" ValidateEmptyText="true">
</asp:CustomValidator>

<script type="text/javascript">
    function CheckDate(source, args) {
        var inputDate = document.getElementById("<%=txtDate.ClientID%>");
        var result = false;

        //validation

        args.IsValid = result;
    }
</script>

如果此后仍有回发,则会出现javasript错误(例如monthLength不存在)。