Custom Validator: Pass custom parameter to clientside validation function from code behind

Hello readers,

It is common we uses all kind of validators in our daily programming. Custom Validator is one of them and may be very interesting too.

Recently i was needed to add one Custom Validator to the page and i was needed to validate a control dynamically based on condition. so that i was needed to pass some custom parameter from code behind to clientside validation function based on which i will determine which control to validate.

Please refer below code to achieve this:

Default.aspx

 <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="txtForm" runat="server"></asp:TextBox>
            <asp:CustomValidator ID="cmtxtForm" runat="server" ClientValidationFunction="OnClientValidate" SetFocusOnError="true"
                ErrorMessage="Please provide valid value" ValidateEmptyText="false" ValidationGroup="FormSubmit">
            </asp:CustomValidator>
            <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" ValidationGroup="FormSubmit" />
        </div>
        <script type="text/javascript">
            function OnClientValidate(sender, args) {
                alert(sender.CustomParameter);
                args.IsValid = sender.CustomParameter;
            }
        </script>
    </form>

Default.aspx.cs

 protected void Page_Load(object sender, EventArgs e)
    {
        bool HasQuerystring = false;
        if (!string.IsNullOrEmpty(Request.QueryString["q"]))
            HasQuerystring = true;
        Page.ClientScript.RegisterExpandoAttribute(cmtxtForm.ClientID, "CustomParameter", HasQuerystring.ToString(), false);
    }

It was so easy right? Thank you 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s