aspnet-web-forms | sharepoint

ASP.NET Web Forms - Manually Trigger Client Side Validation

You can manually trigger client-side validation for ASP.NET Web Forms Server side controls. One way of doing it explained here.

Abhith RajanJanuary 15, 2018 · 2 min read · Last Updated:

Lets say you have a web form with one more serverside controls like one below,

1<asp:TextBox ID="txtEmail" runat="server" class="txtBoxLarge textSmall" placeholder="Enter Email Address"></asp:TextBox>
2
3<asp:RequiredFieldValidator ID="rfvEmail" runat="server" ErrorMessage="Enter Email" Display="None" ControlToValidate="txtEmail" ValidationGroup="groupName"></asp:RequiredFieldValidator>

And you need to do some client side operations along with client side validation, the button triggering the whole operation will be like,

1<asp:Button ID="btnSubmit" CssClass="blueBtnLarge" runat="server" Text="Continue" ValidationGroup="groupName" OnClick="btnSubmit_Click" OnClientClick="ClientSideClick(this)" UseSubmitBehavior="False" />

Here OnClick will send request to server side and OnClientClick will execute on client side before control passed to server. OnClick only will be triggered if OnClientClick returned true.

And the client side JavaScript function we call on OnClientClick will be like below,

1<script type="text/javascript">
2 function ClientSideClick(myButton) {
3 // Any operation before validation goes here
4
5 // Client side validation
6 if (typeof (window.Page_ClientValidate) == 'function') {
7 if (window.Page_ClientValidate('groupName') === false) {
8 document.getElementById('someDivElementWithErrorExplanation').style.display = 'block'; // Showing error on validation, modify to your needs
9 return false;
10 }
11 }
12 document.getElementById('someDivElementWithErrorExplanation').style.display = 'none';
13
14 // Any operation after client side validation passess goes here.
15
16 return true;
17 }
18</script>

That’s it. Also, don’t forget to notice the usage of the ValidationGroup all over the code above.

Written by Abhith Rajan
Abhith Rajan is an aspiring software engineer with more than 8 years of experience and proven successful track record of delivering technology-based products and services.
Buy me a coffee

Was this helpful?

Show some ❤️

Share this page on Twitter to appear on the webmentions* 💡

This page is open source. Noticed a typo? Or something unclear?
Improve this page on GitHub