Click here to Skip to main content
15,886,362 members
Articles / Mobile Apps
Article

Custom Control For Common RequiredField Validator

Rate me:
Please Sign up or sign in to vote.
3.35/5 (11 votes)
4 Oct 20042 min read 54K   242   11   1
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

Introduction

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.

C#
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.

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

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

/// <SUMMARY>
/// 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.

C#
/// <SUMMARY>
/// Add TextBox control and Display message to private ArrayList
/// </SUMMARY>
public void AddControlToValidate(TextBox objCtl,string strErrorMessage)
{
    objList.Add(objCtl); 
    arrErrorMessage.Add(strErrorMessage);
}

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

C#
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['"+ 
                           ((TextBox)objList[i]).ID+"'].value==''){");
  //Add Alert is Type is set to Alert else 
  //build the error message string to be displayed
  if(iAlertType==0)
  {
    strJavaScript.Append(@"alert('"+ (string)arrErrorMessage[i] + 
                          "');document.all['"+((TextBox)objList[i]).ID+ 
                          "'].focus();return false;}");
  }
  else
  {
    strJavaScript.Append(@"msg=msg+'<li>"+
                         (string)arrErrorMessage[i]+"</li>';}"); 
  }
}

if(iAlertType==1)
{
  strJavaScript.Append(@"if(msg!=''){document.all['"+ 
            this.ID+"'].innerHTML=msg+'</ui>';return false;}");
}

strJavaScript.Append(@"return true;}</script>");
Page.RegisterClientScriptBlock("funValidate",strJavaScript.ToString());

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

C#
protected override void OnInit(EventArgs e)
{
  base.OnInit (e);
  Page.RegisterOnSubmitStatement("GroupValidation", 
                  "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.

C#
protected override bool EvaluateIsValid()
{
  if(objList.Count==0)
  {
    // 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()) ;
  }
  else
  {
    bool result=true;
    string strmsg="";
    for(int i=0;i < objList.Count;i++)
    {
      if(((TextBox)objList[i]).Text.Trim().Equals(InitialValue.Trim()))
      {
        strmsg+="\n"+(string)arrErrorMessage[i];
        result=false;
      }
    }
    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.

History

  • Created on 4th October, 2004.

License

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


Written By
Architect
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
blogs
at WebDevs.com.

Comments and Discussions

 
Generalclient side validation not working Pin
sacchit28-Jun-06 3:03
sacchit28-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.