戰地連結︰ Home My Flickr NBA.com About

2009年7月8日星期三

Client side validation skipped if submit Button have "onClientClick" JavaScript function

Overview

I have a form using ASP.NET validation controls, I have been using these ASP.NET validators for quite a time and they behaved well. However the problem come when I added a "onClientClick" event handler to the form submit button, and then the validation is just skipped and the form post back every time.

The problem is that the "onClientClick" event get fired before the validation so the validation is skipped. To solve this, we can use the JavaScript function "Page_ClientValidate()" to trigger the client side validation.

Reference

asp:Button Validation with OnClientClick javascript - Not Validating

ASP.NET Validation in Depth

Code Snippet

You can tell "Page_ClientValidate()" to only validate controls of a particular validation group by passing the validation group name as parameter.

function BtnSubmitButton_click()

        {

            if (Page_ClientValidate("ValidationGroup"))

            {

                return confirm("Submit this form?");

            }

            return false;

        }

沒有留言: