Saturday, September 17, 2011

Client side custom validator in repeator control

Hi All,
Today I used custom validator inside a repeator and since this was first time I used this I thought to share it here.
 Scenario: I was having a repeator with two textboxes per row (one for installment amount and other for installment duration) and I was supposed to implement a client side validation that will force user to insert value in duration textbox, if he inserts value in amount textbox.
The code that I came up with was some-what like below:

Repeator was like this:

                    <%#(((RepeaterItem)Container).ItemIndex+1).ToString() %>:
                    <asp:TextBox ID="txtPaymentPlanAmount" runat="server" />    Due In
                    <asp:TextBox ID="txtPaymentPlanDuration" runat="server" />
                    <asp:CustomValidator ID="cvPaymentPlanDuration" runat="server" ValidationGroup="PricingPlanValidator"
                        Display="Dynamic" CssClass="errMsg" EnableClientScript="true" Text="*" ErrorMessage="You have set the amount but not duration." ClientValidationFunction="PaymentPlanDurationValidator":CustomValidator>
                    <asp:DropDownList ID="ddlPaymentPlanDuration" runat="server">
 ValidationGroup="PricingPlanValidator" />
And validator method was like this:

<script type="text/javascript">
function PaymentPlanDurationValidator(sender, args) {
            var id =;
            var amountTextBoxName = id.replace("cvPaymentPlanDuration", "txtPaymentPlanAmount");
            var durationTextBoxName = id.replace("cvPaymentPlanDuration", "txtPaymentPlanDuration");

            var amountTextBox = document.getElementById(amountTextBoxName);
            var durationTextBox = document.getElementById(durationTextBoxName);

            if (amountTextBox.value) {
                  if (durationTextBox.value) {
                        args.IsValid = true;
} else {
                        args.IsValid = false;
                  else {
args.IsValid = true;


This method is called automatically by custom validator for each row. Here I replaced textbox ids with custom validator id to get runtime clientside name of textboxes (as in highlighted code lines) and the rest is simple javascript logic.

args.IsValid, this lets validator know that wether or not current row satisfies the desired condition.

No comments:

Post a Comment

About Me

My photo
Delhi, India
Fun, music, travel and nature loving, always smiling, computer addict!!