Products
Services
Contact Us

Scripts: C# :: Validation :: Library Article #12

Developer's Section

Using Validator Objects to validate form data on the client side without using postbacks in C#.
By: Erobo Team Member

Hire a Developer for Related Work / Installation | $55 hr
Rating:  | Rate It:   
Average Votes: (3626)
Favorites:

In this article we describe how to validate form data using RequiredFieldValidators and CustomValidator on the client side without using postbacks.

There is a way to fire the validators you create on your aspx page without triggering a postback. If you assign the validators to a Validation Group, then you can easily trigger an event that will fire each and everyone of the validators without submitting the page by using Page_ClientValidate('My Group').
In the example below we will use a simple asp TextBox and a Telerik RadListBox to illustrate this idea.

Code page for myformExample.aspx:

 Code Snippet 1

<%@ Page Title="" Language="C#" AutoEventWireup="true" 
CodeBehind="myformExample.aspx.cs" Inherits="Dev.FormExample" %>
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" 
Assembly="Telerik.Web.UI" %>

<script language="javascript">

var itemsTakenRef = '<asp:Literal id="CountryRef" runat="server" />';

function CheckCountrySelected(source, args) {

  var CountrySelection_Client = $find(itemsTakenRef);

  var clientsArr = CountrySelection_Client.get_items();

  if (clientsArr.get_count() == 1) {
    if (clientsArr.getItem(0).get_value() == "0") {
      args.IsValid = false;
    } else {
      args.IsValid = true;
    }
  } else {

    if (clientsArr.get_count() == 0) {
      args.IsValid = false;
    } else {
      args.IsValid = true;
    }
  }
}

function validate_Form_Users() {

  //Do some stuff before triggering validators

  var CountrySelection_Client = $find(itemsTakenRef);
  var iniCount = CountrySelection_Client.get_items().get_count();
  var itemArr = null;
  var currItem = null;
  for (var y = 0; y < iniCount; y++) {
    itemArr = CountrySelection_Client.get_items();
    currItem = itemArr.getItem(y).set_selected(true);
  }

  //trigger validators

  Page_ClientValidate('Group1');

}

</script>

<asp:form id="form1" runat="server">
<table border="0" cellpadding="2" cellspacing="2" width="100%">
  <tr>
    <td valign="top" class="style1"> </td>
    <td valign="top" align="right" colspan="3">

      <!-- Important: 
           Use OnclientClick to assign the onsubmit event of the form-->

      <asp:Button runat="server" ID="btnSend" 
      Text=" Submit " onclientclick="return validate_Form_Users()"/>
        
      <input type="button" value="Back To List" 
      onclick="javascript: self.location.href='myformList.aspx';">
    </td>
  </tr>
  <tr>
    <td valign="top" class="style2">UserName:</td>
    <td valign="top" colspan="3">
      <asp:TextBox runat="server" id="username_text"  size="35"  />

      <!--Declare validator 1-->
      <asp:RequiredFieldValidator runat="server" ID="custVal1" 
      ErrorMessage="Please, enter an username!" 
      ControlToValidate="username_text" ValidationGroup="Group1" /> 

    </td>
  </tr>
  <tr>
    <td valign="top" class="style2">Country:</td>
    <td valign="top" colspan="3">
      <!--start telerik control-->
      <telerik:RadListBox
        runat="server" ID="country_text" SelectionMode="Multiple"
        Height="120px" Width="200px"
        AllowTransfer="true" TransferToID="country_selection">
      <Items>
        <telerik:RadListBoxItem Text="Select One.." Value="0" />
        <telerik:RadListBoxItem Text="Argentina" Value="1" />
        <telerik:RadListBoxItem Text="Australia"  Value="2" />
        <telerik:RadListBoxItem Text="Brazil" Value="3" />
        <telerik:RadListBoxItem Text="Canada" Value="4" />
      </Items>
      </telerik:RadListBox>

      
      <telerik:RadListBox SelectionMode="Multiple"
        runat="server" ID="country_selection"
        Height="120px" Width="160px" />

      <!--Declare validator 2-->

      <asp:CustomValidator ID="custVal1" ControlToValidate="country_selection"
      ClientValidationFunction="CheckCountrySelected"
      OnServerValidate="cvText_CheckCountrySelected" 
      ErrorMessage="Select a Valid Country" Display="Dynamic" 
      ValidationGroup="Group1" 
      EnableClientScript="true"  
      runat="server" > </asp:CustomValidator>

      <!--Declare validator 3-->

      <asp:RequiredFieldValidator runat="server" ID="custVal2"
      ErrorMessage="Please, select item!" ControlToValidate="country_selection"
      ValidationGroup="Group1" />  


      <!--end telerik control-->
    </td>
  </tr> 
</table>
</asp:form>


Now, on the code Behind (myformExample.aspx.cs):

 Code Snippet 2

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Telerik.Web.UI;

namespace Dev
{
  public partial class FormExample : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      CountryRef.Text = country_selection.ClientID;

      if (!Page.IsPostBack){
        //do something
      }
            
    }

    //Validate on the Server Side here if necessary
    protected void cvText_CheckCountrySelected(object source, 
                             ServerValidateEventArgs args)
    {
      //Do some stuff
      args.IsValid = true;
    }
  }
}


When the user hits submit the validators will be triggering one by one, causing the form data to be validated instantly. Good Luck!!


See other Scripts in Validation

Submit Your Scripts:


System Message:
  • Your C# script has been sent. Please allow 48 hours for processing.


If you would like to have your Javascripts published in this section please fill out
the form below:
*Your Name or Username:
Home Town:
*Email:
*Description and Code:
*Enter Code shown
to the right:

[ Refresh Image ]