简体   繁体   中英

how to prevent CustomValidator from doing PostBack

I've been trying to to a validation check to a date field, but it keeps doing post back and not working.. Here is the HTML:

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

and the function in 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;
    } 

but no success.. how do i prevent it from happening?

Try adding ValidateEmptyText="true" . And change the way you return the result.

<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>

If there is still postback after this then there are javasript errors (like monthLength not existing).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM