Show a JavaScript confirm dialog box after client validation

It’s quite common to use a JavaScript confirm dialog on a button press to ensure that the user wants to submit the page.  If you are using any of the ASP.NET validators that use client side validation you will find the confirm appears before the validation, whereas it would be better if the confirm box only appeared if the page was valid.

Luckily the framework supplies some JavaScript functions that can be used for validation.  Page_IsValid is a boolean indicating if the page is valid which can be used in client script.  This value is set when the JavaScript function Page_ClientValidate is executed.

For this example I have set CausesValidation to false on the button that will show the confirm dialog, as I will call the client side function myself.  If I don’t to this my validation will be called twice.  In the OnClientClick I then need to add some JavaScript to call Page_ClientValidate if the function exists, and then only show the confirm dialog if Page_IsValid is true:

<asp:LinkButton ID="btnSubmit"
                OnClientClick="if (typeof(Page_ClientValidate) == 'function') { Page_ClientValidate(); if(Page_IsValid) { return confirm('You are sure?'); } };"
Posted on by Joe in ASP.NET, C#, JavaScript

7 Responses to Show a JavaScript confirm dialog box after client validation

  1. Madge

    Nice simple example – just what I was looking for.
    Thanks for sharing.

  2. RAHUL

    Simple and awesome code. Thanks for sharing

  3. Joe

    Glad you found it useful Rahul

  4. Vamsi

    Thanks bro it really helped… I tried for this for 1 whole day over the google and ends up here.

  5. Vamsi

    this is also working fine….

  6. Jake

    Very Very Good. Simple and it works. Thanks

  7. Kang Usep

    Thx Bro … You save my day

Add a Comment