Sep 10, 2011

Client Side Validation using ASP.NET Validator Controls from Javascript

ASP.NET validation controls provide functionality to perform validation using client script. By default, when client-side validation is being performed, the user cannot post the page to the server if there are errors on the page thus the user experience with the page is enhanced.

Client-side objects:

Page_IsValid

Boolean variable

Indicates whether the page is currently valid. The validation scripts keep this up to date at all times.

Page_Validators

Array of elements

This is an array containing all of the validators on the page.

Page_ValidationActive

Boolean variable

Indicates whether validation should take place. Set this variable to False to turn off validation programmatically.

isvalid

Boolean property

This is a property on each client validator indicating whether it is currently valid.

Page_ValidationSummaries

Array of elements

This is an array containing all of the validation summaries on the page.

Client-Side APIs:

ValidatorValidate(val)

Takes a client-validator as input. Makes the validator check its input and update its display.

ValidatorEnable(val, enable)

Takes a client-validator and a Boolean value. Enables or disables a client validator. Being disabled will stop it from evaluating and it will always appear valid.

ValidatorHookupControl(control, val)

Takes an input HTML element and a client-validator. Modifies or creates the element's change event so that it updates the validator when changed. This can be useful for custom validators that depend on multiple input values.

Page_ClientValidate(val)

Takes validation group as input and validate all validators of the group and returns bool.

Sample Code:

Let us take an example to understand, consider following asp.net code:


 <div>
        <fieldset class="login">
            <legend>Account Information</legend>
            <p>
                <asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">Username:</asp:Label>
                <asp:TextBox ID="UserName" runat="server" CssClass="textEntry"></asp:TextBox>
                <asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName"
                    CssClass="failureNotification" ErrorMessage="User Name is required." ToolTip="User Name is required."
                    ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator>
            </p>
            <p>
                <asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>
                <asp:TextBox ID="Password" runat="server" CssClass="passwordEntry" TextMode="Password"></asp:TextBox>
                <asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password"
                    CssClass="failureNotification" ErrorMessage="Password is required." ToolTip="Password is required."
                    ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator>
            </p>
            <p>
                <asp:CheckBox ID="AllowMe" runat="server" />
                <asp:Label ID="RememberMeLabel" runat="server" AssociatedControlID="AllowMe" CssClass="inline">Allow me without password</asp:Label>
            </p>
        </fieldset>
        <p class="submitButton">
            <asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Log In" ValidationGroup="LoginUserValidationGroup"
                OnClientClick="performCheck();" />
        </p>
    </div>
client side validation

Case I: Validate the Group:

In our example, See following code to validate LoginUserValidationGroup:


function performCheck() {
            Page_ClientValidate("LoginUserValidationGroup");
            if (Page_IsValid) {
                alert('it is valid');
                return true;
            }
            else {
                alert('No valid');
                return false;
            }
        }

In other way, you can directly use Page_ClientValidate method:


function performCheck() {         
           if (Page_ClientValidate("LoginUserValidationGroup")) {
                alert('it is valid');
                return true;
            }
            else {
                alert('No valid');
                return false;
            }
        }

Case II:

To understand other client side objects and APIs, let us validate LoginUserValidationGroup without using Page_ClientValidate.

function performCheck() {
            if (checkValidationGroup("LoginUserValidationGroup")) {
                alert('it is valid');
                return true;
            }
            else {
                alert('No valid');
                return false;
            }
        }
   
        function checkValidationGroup(valGrp) {
            var rtnVal = true;
            for (i = 0; i < Page_Validators.length; i++) {
                if (Page_Validators[i].validationGroup == valGrp) {
                    ValidatorValidate(Page_Validators[i]);
                    if (!Page_Validators[i].isvalid) { //at least one is not valid.
                        rtnVal = false;
                        break; //exit for-loop, we are done.
                    }
                }
            }
            return rtnVal;
        }

In checkValidationGroup method, first validation group of all validators on page is checked. If it belongs to given group, it is validated. If it is not valid, the method will return false.

Case III: Enable/Disable Validator:

Suppose you have to disable password requiredfield validator If 'Allow me' checkbox is true. See following code:


  function performCheck() {
 
            if (document.getElementById('<%=AllowMe.ClientID%>').checked) {
                ValidatorEnable(document.getElementById('<%=PasswordRequired.ClientID%>'), false);
            }

            if (Page_ClientValidate("LoginUserValidationGroup")) {
                alert('it is valid');
                return true;
            }
            else {
                alert('No valid');
                return false;
            }
        }

Hope It helps!!!