Click here to Skip to main content
13,000,982 members (59,135 online)
Click here to Skip to main content
Add your own
alternative version


11 bookmarked
Posted 4 Oct 2004

Custom Control For Common RequiredField Validator

, 4 Oct 2004
Rate this:
Please Sign up or sign in to vote.
Common validation conrol for more than one Required Field on the page. The simple and most eligant way to validate required fields.

Sample Image - GroupValidatorSummary.gif


Initially, I was impressed by ASP.NET Validation controls. But as I started using these controls, I got annoyed by the fact that we can not use the same validation control for more than one control. So if you have more "required fields", you will end up with more number of RequiredFieldValidators. The second problem was we can not mimic the old day JavaScript validation which will alert the user for specific field and set the focus on it. So, I decided to create one custom Validation Control which can serve both purposes.

Using the code

This control is very easy to use, much similar to normal RequiredFieldValidator control.

If you have only one required field, this control will behave similar to the RequiredFieldValidator control.

If you have a group of controls to validate, then use AddControlToValidate (TextBox, ErrorMessageToBeDisplay) on Page_Load. You can set alert type also. By default, it will popup alert message to user and set the focus to the required field.

private void Page_Load(object sender, System.EventArgs e)
    GroupReqValidator1.AddControlToValidate(TextBox1, "Please Enter Date ");
    GroupReqValidator1.AddControlToValidate(TextBox2, "Please Enter Name");
    GroupReqValidator1.AddControlToValidate(TextBox3, "Please Enter Surname");

Points of Interest

So, let's start unwrapping the magic behind this control. It's very simple. As I want to build a group RequiredFieldValidator control, I inherited my class from System.Web.UI.WebControls.RequiredFieldValidator, so that we will get all basic functions implemented.

First of all, we require some kind of collection to store the references for the control(s) to be validated and the appropriate message to be displayed. So, I used ArrayList, and a variable to store the display style.

/// ArrayList to Hold objects to be Validated
/// </SUMMARY>
private System.Collections.ArrayList objList= 
                    new System.Collections.ArrayList();

/// ArrayList to Hold Message when Object is not Valid
/// </SUMMARY>
private System.Collections.ArrayList arrErrorMessage= 
                    new System.Collections.ArrayList();

/// Style to be used to display the error message
/// </SUMMARY>
private int iAlertType=0;

Next, create a function to add control and message to this ArrayList.

/// Add TextBox control and Display message to private ArrayList
/// </SUMMARY>
public void AddControlToValidate(TextBox objCtl,string strErrorMessage)

Next, we need to generate client script to validate all controls and display alert if needed. I did this job in OnPreRender function.

System.Text.StringBuilder strJavaScript=new System.Text.StringBuilder();

//Generate the Validation Event to Validate control
strJavaScript.Append(@"<script JavaScript?? langauge="">"); 
strJavaScript.Append(@"function ValidateGroupControl(){var msg='<ui>';");
for(int i=0;i<objList.Count;i++)
  strJavaScript.Append(@"if( document.all['"+ 
  //Add Alert is Type is set to Alert else 
  //build the error message string to be displayed
    strJavaScript.Append(@"alert('"+ (string)arrErrorMessage[i] + 
                          "'].focus();return false;}");

            this.ID+"'].innerHTML=msg+'</ui>';return false;}");

strJavaScript.Append(@"return true;}</script>");

Once script is registered, we need to call this script when the Form is submitted. That we can do using RegisterOnSubmitStatement function to register.

protected override void OnInit(EventArgs e)
  base.OnInit (e);
                  "return ValidateGroupControl();");

So far so good. Now, client side validation is done. But what if JavaScript is disabled? So, we have to implement server side validation, too. We can do this by implementing EvaluateIsValid.

protected override bool EvaluateIsValid()
    // Get the control value; return true if it is not found.
    string controlValue = GetControlValidationValue(ControlToValidate);
    if (controlValue == null) 
      //Debug.Fail("Should have been caught by PropertiesValid check.");
      return true;
    // See if the control has changed.
    return !controlValue.Trim().Equals(InitialValue.Trim()) ;
    bool result=true;
    string strmsg="";
    for(int i=0;i < objList.Count;i++)
    this.ErrorMessage = strmsg;

    return result;

Here you go.. Build this control library, add reference to your project, and enjoy validating. Do drop me comments ..please.


  • Created on 4th October, 2004.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Gaurang Desai
United States United States
Currently he is working as Senior Soft. Engineer at Cognizant Technology Solution.He is involved in various project activities like System Architecture, Design, and Development. He is fond of conduction training for various technologies. He has have worked on various language and platforms. He is Microsoft and Oracle Certified professional. He is spending quantity and quality time in .Net world. He had also spoiled his hand with java, too.
If work is not demanding, he spends good time with his wife, Purvi.He

You may also be interested in...


Comments and Discussions

Generalclient side validation not working Pin
sacchit28-Jun-06 3:03
membersacchit28-Jun-06 3:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170624.1 | Last Updated 4 Oct 2004
Article Copyright 2004 by Gaurang Desai
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid