Thursday, September 2, 2010

CustomValidator validation in Repeater with RegisterExpandoAttribute and ClientValidationFunction JavaScript

Hi All,

ASP.Net comes with many validators, one of the validator is CustomValidator. We can use custom validator in 2 ways, either client side or server side validation.

In this post I will provide information specifically on client side validation. Client side validation is achieved with JavaScript function. JavaScript function sample is as below

function MyClientValidation(source, arguments) {
       if ( your validation condition ){
            arguments.IsValid = true;
       } else {
            arguments.IsValid = false;
       }
}

 

Now we will call above function with ClientValidationFunction property of custom validator mentioned as below.

   1:  <asp:CustomValidator ID="MyValidator" runat="server" ClientValidationFunction="MyClientValidation"></asp:CustomValidator>

 

It is simple to call client validation function with a custom validator.

Now you must have question, why I am writing this basic thing for a client validation. Client validation function is really simple when we write validator and control which we are validating both are on page directly. But there is a scenario where this simple method will not work.

In this post I will explain how to use CustomValidator with client side validation when validator is within a Repeater or a ListView control.

We will go through scenario when a CustomValidator is inside a Repeater control. We will have 3 items in Repeater.

  1. A CheckBox control
  2. A TextBox control
  3. And a CustomValidator

Now as per scenario we need to validate TextBox text when check box for same row is selected.

Below will be html for the Repeater:

<asp:Repeater ID="rptItem" runat="server" OnItemDataBound="rptItem_ItemDataBound">
      <HeaderTemplate>
          <table>
      </HeaderTemplate>
      <ItemTemplate>
          <tr>
              <td>
                  <asp:CheckBox ID="chkSelectItem" runat="server" />
              </td>
              <td>
                  <asp:TextBox ID="txtToValidate" runat="server"></asp:TextBox>
              </td>
              <td>
                  <asp:CustomValidator ID="cValidation" runat="server" ClientValidationFunction="MyClientValidation"
                      ErrorMessage="Invalid"></asp:CustomValidator>
              </td>
          </tr>
      </ItemTemplate>
      <FooterTemplate>
          </table>
      </FooterTemplate>
</asp:Repeater>

I have registered item data bound event over here to do some code.

We have set the html for our scenario, now custom validator need to validate only those textbox for which corresponding checkbox is selected. We will achieve it with ClientScript.RegisterExpandoAttribute method. ClientScript.RegisterExpandoAttribute is used to register custom attributes for your ASP.Net server controls on runtime. Below is the code to register custom attributes.

protected void rptItem_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
      if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
      {
          CheckBox chkSelectItem = e.Item.FindControl("chkSelectItem") as CheckBox;
          TextBox txtToValidate = e.Item.FindControl("txtToValidate") as TextBox;
          CustomValidator cValidation = e.Item.FindControl("cValidation") as CustomValidator;

          if (chkSelectItem != null && txtToValidate != null && cValidation != null)
          {
              ClientScript.RegisterExpandoAttribute(cValidation.ClientID, "chkId", chkSelectItem.ClientID);
              ClientScript.RegisterExpandoAttribute(cValidation.ClientID, "txtId", txtToValidate.ClientID);
          }
      }
}

 

Once we register above method in code behind of page and run the page, it will register some script dynamically as below.

var MainContent_rptItem_cValidation_0 = document.all ? document.all["MainContent_rptItem_cValidation_0"] : document.getElementById("MainContent_rptItem_cValidation_0");
MainContent_rptItem_cValidation_0.chkId = "MainContent_rptItem_chkSelectItem_0";
MainContent_rptItem_cValidation_0.txtId = "MainContent_rptItem_txtToValidate_0";
MainContent_rptItem_cValidation_0.errormessage = "Invalid";
MainContent_rptItem_cValidation_0.evaluationfunction = "CustomValidatorEvaluateIsValid";
MainContent_rptItem_cValidation_0.clientvalidationfunction = "MyClientValidation";

 

Now we need to modify our JavaScript function in such a way that will use our custom registered attributes to validate the control. Modification is as below.

 
function MyClientValidation(source, arguments) {
      var chkBox = document.getElementById(source.attributes["chkId"].value);
      var txtBox = document.getElementById(source.attributes["txtId"].value);
      if (chkBox.checked == true) {
          var re = new RegExp("[0-9]+");
          if (re.test(txtBox.value)) {
              arguments.IsValid = true;
          }
          else {
              arguments.IsValid = false;
          }
      } else {
          arguments.IsValid = true;
      }
}

 

Now we have set all, our validation function will validate textbox with numeric value and non empty and should only validate those textboxes for which checkbox is checked.

Here is the output of our code.

image

You can modify the JavaScript function as per your requirement. also you can register more expando attributes if you require. But note that it will rendered on the client side and will considerably increase your client script.

Now if you are binding your repeater in an UpdatePanel then you need to register the expando attribute somewhat differently as below

   1:  ScriptManager.RegisterExpandoAttribute(MyUpdatePanel, cValidation.ClientID, "chkId", chkSelectItem.ClientID);
   2:  ScriptManager.RegisterExpandoAttribute(MyUpdatePanel, cValidation.ClientID, "txtId", txtToValidate.ClientID);

Hope you liked this post and it helped you.

Any question or suggestion is welcome.

 

Thanks,

Nirav

5 comments:

  1. Hi, thank you , interesting , but there was a problem ,i think , if you have an update panel , and you submit succefully the form , next time (itemdatabound does not fire again ) you are unable to validate again repeaters, attribute was cancelled.
    Hi

    ReplyDelete
  2. Yes, you are correct about that. But it is not only for update panel. If your page PostBack then also your databind event will not raised again and attribute will be canceled.

    In this scenario you can create another method to register this attributes for all the items in your listview or repeater.

    ReplyDelete
  3. Thanks so much. I haven't tested this yet, but was curious about how you would do this with server side validation.

    Thanks so much.

    ReplyDelete
  4. I have tried everything on this page with my own page. Nothing you posted here worked for me. 3 hours i have been trying to get this to work and nothing..

    ReplyDelete
  5. You should try to replace source.attributes["chkId"].value for source.chkId;

    ReplyDelete

Comments posted on ASP.Net Ajax Tutorials Blog are moderated and will be approved only if they are on-topic and not abusive. Please email me or my team for tech-support or blogging related questions. Avoid including website URLs in your comments - Thanks Author