ASP.NET Client-side Validation & Confirmation Popup
The other day I was working on a project for our client. They wanted some client-side validation to be done on the page to avoid postbacks, since postbacks could take REALLY long on a slow connection. They also wanted a javascript confirmation popup before processing the form.
In the page, I had a few RequiredFieldValidators, as well as some RegularExpressionValidators. Initially, I modified the submit button to include the confirmation message, and check whether the page is valid or not. Below is a snippet of the ASP.NET button that I had in my page.
<asp:button text="Submit" onclientclick="return (Page_IsValid && confirm('Are you sure?'));" onclick="Button1_Click" runat="server" id="Button1"></asp:button>
Note: Page_IsValid is the client-side version of Page.IsValid that we are used to in codebehind.
Now, here's the problem I was facing the other day. After the page had loaded successfully, I immediately clicked on the submit button to test the validation on the page. Supposedly, error messages should be displayed because the form was not completed, and I have RequiredFieldValidators and RegularExpressionValidators all over the page. But instead, the javascript confirmation popped up. After I clicked OK, then only the error messages came out. Subsequent clicks on the Submit button did not pop up the confirmation message anymore.
From my observation, it seems that Page_IsValid is returning true the first time the page loads, and holds true until we click the submit button the first time. This means that the client-side validation is only being done after our javascript snippet that we have in the OnClientClick event.
A few Google searches showed me that I have to manually call a javascript function Page_ClientValidate() to validate the form. This function is included with the .NET Framework. By calling this function, it will force to update the Page_IsValid variable. The working code in my aspx now is:
<asp:button text="Submit" onclientclick="Page_ClientValidate(); return (Page_IsValid && confirm('Are you sure?'));" onclick="Button1_Click" runat="server" id="Button1"></asp:button>
Hope that helps someone out there.
Recent comments
14 weeks 2 days ago
1 year 2 days ago
1 year 3 weeks ago