Tuesday, 28 July 2009

ASP.NET: How to trigger the client-side validation manually

By default the client-side validation is triggered when submitting forms using buttons. However, sometimes you may want to trigger client-side validation on your ASP page manually from custom Javascript. You can achieve that by calling Javascript validation functions provided by the ASP.Net framework directly from your custom code.

The following page source example displays a TextBox and its validation controls (RequiredFieldValidator & ValidationSummary). The validation controls have the same ValidationGroup defined, which allows us to validate different page elements independently. The page displays also a DIV element that will cause the Validation action when clicked:
<!-- Validation Summary -->
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
HeaderText="Validation errors:" ValidationGroup="Group1"/>

<!-- TextBox and its validator -->
Name: <asp:TextBox ID="TextBox1" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Name is required" Text="*"
ControlToValidate="TextBox1" ValidationGroup="Group1"> />

<!-- Div that causes client-side validation when clicked -->
<div onclick="Validate();" >Validate Form</div>

The code above should should produce smth like that when validation is triggered:

Validation form
Now let's take a look at the custom JS code that triggers the validation. There are couple ways to do that:
  • Easy way - works for all validators from the same ValidationGroup:
    function Validate()
    {
    // If no group name provided the whole page gets validated
    Page_ClientValidate('Group1');
    }
  • If you want to validate only specific validators:
    function Validate()
    {
    // Get the specific validator element
    var validator = document.getElementById('RequiredFieldValidator1');

    // Validate chosen validator
    ValidatorValidate(validator);

    // Update validation summary for chosen validation group
    ValidatorUpdateIsValid();
    ValidationSummaryOnSubmit(validationGroup);
    }

Useful links:

5 comments:

Joonha said...

This is very useful. I used this in combination with jquery to handle blur and click events for validating checkboxes (terms and conditions) and radio choices being selected. Good stuff man, my validations are all synced with asp.net. I appreciate it.

SpaceGhost said...

Very helpfull thank you!

jrluh said...

Wow! You've just helped me solve a pretty stupid requirement. Thanks!

Diana182 said...

Loved it! thank you.

Ketaki said...

I had been using Page_ClientValidation but recently this has been failing for Mac users. It cannot recognize the Page_ClientValidation and just passed through it.