简体   繁体   中英

JavaScript client side function not firing for ASP custom validator

I have the following ASP CustomValidator:

<asp:CustomValidator ID="CustomValidator2" runat="server"
    EnableClientScript="true" OnServerValidate="ins_server"  ClientValidationFunction ="ins_client" 
    ErrorMessage="CustomValidator"> * Insurance dates not valid without supporting attached document</asp:CustomValidator>

The following C# server side function:

protected void ins_server(object source, ServerValidateEventArgs args)
{
    //new user
    if (PageMode == PageModes.NewVessel)
    {
        if (fuAttachment.HasFile && datetimepickerinsend != null && datetimepickerinsstart != null)
        {
            args.IsValid = true;
        }              

        else
        {
            args.IsValid = false;
        }
    }    

    //existing user
    if (PageMode == PageModes.EditVessel)
    {
        args.IsValid = true;
    }
}

And also the following client side function in JavaScript stored in a file named customfunctions.js:

//declerations
var insurancestart;
var insuranceend;
var filesattached;

function ins_client(sender, e) {
    if (pagemode == 'EditVessel') {
        e.IsValid = true;
    }

    if (pagemode == 'NewVessel') {
        if (insurancestart !== '' && insuranceend !== '' && filesattached > 0) {
            e.IsValid = true;
        }
        else {
            e.IsValid = false;
        }
    }
}

I also have the following global variable definition in the ASPX page the control sits on:

 <script type="text/javascript">

     var pagemode;
     $(document).ready(function () {
         // removed var to give global scope
         pagemode = '<%=this.PageMode.ToString()%>';                         
     });
</script>

My problem is I have placed a breakpoint on the server side function, every time I click the submit button the server side code is being called and the page refreshes. If I debug in chrome I can see that all my JS variables have the expected values, it just seems like for some reason the client side JS function is not firing and is instead falling over to the server side function.

What was happening here was as @Justin-iurman pointed out, when the function returns true the server side function will also be called after the client. In my case though when I tested a false result I was still going straight to the server side function.

Turns out by pressing F12 in chrome and inspecting the console, I had an undefined error in my JS code. Moving the function in question out of the function used specifically for this page and into global context sorted the issue for me.

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