Click here to Skip to main content
13,090,178 members (50,121 online)
Click here to Skip to main content
Add your own
alternative version


29 bookmarked
Posted 11 Oct 2004

Combine RegularExpression Validation Control with RequiredField Validation Control

, 11 Oct 2004
Rate this:
Please Sign up or sign in to vote.
RequiredField and Regular Expression validation together... you can use this control in place of group required field and regular expression validation controls.

Sample Image - CommonRegExpValidation.jpg


After successfully implementing the Common Required Field Validator, many friends asked me to implement a Regular Expression Field Validator which can also do required field validation at the same time. It seems very useful if we can combine it together... So here you are... I have come up with a common Regular Expression Field Validator with option to do required field validation too.

Using the code

This control is very easy to use, much similar to normal Regular Expression Field Validation control. If you have only one regular expression field, this control will behave similar to Regular Expression Field Validation Control. If you have a group of controls to validate, then use AddControlToValidate(TextBox Control, ErrorMessageToBeDisplay) on Page_Load. You can set Alert type as Alert window(0) or Summary(1). By default, it will popup alert message to user and set the focus to 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

Sounds interesting..!!! So, let's start exploring the magic behind this control. It’s very simple. As I wanted to enhance Required Field Validator, I derived my class from System.Web.UI.WebControls.RequiredFieldValidator, so that we will get all basic functions implemented, at no cost!!! As we want to deal with a group of controls, we require some kind of collection to store the reference for the control(s) that are to be validated and the same way appropriate message(s) to be displayed, when validation rule is violated. I use ArrayList for this purpose and one variable to store the display style.

/// ArrayList to Hold objects to be validated
  private System.Collections.ArrayList objList= 
                           new System.Collections.ArrayList(); 

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

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

Adding Method to Add Fields and Message to control

Create one function to add control and message to this ArrayList:

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

Validation will take place at two places. First at client side and then at server side. For client side validation, we need to generate client script. I did this job in OnPreRender function.

protected override void OnPreRender(EventArgs e)
    base.OnPreRender (e);

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

    //Generate the Validation Event to Validate control
    strJavaScript.Append(@"<script langauge=""JavaScript"">"); 
    strJavaScript.Append(@"function ValidateGroupRegControl()" + 
               @"{var re = new RegExp('"+ 
               ValidationExpression.Replace("\\","\\\\") + 
               "');var m='';var msg='';");
    for(int i=0;i<objList.Count;i++)
        strJavaScript.Append(@"if( m == null || m[0]!=document.all['"

              ((TextBox)objList[i]).ID+"'].value=='') return true;");

        //Add Alert is Type is set to Alert else build 
        //the error message string to be displayed
                    "'].focus();return false;}");//
                 this.ID+"'].visibility);return false;}"); 
    strJavaScript.Append(@"return true;}</script>");

Once script is registered, we need to call this script when the Form is submitted. We can register JavaScript that needs to be called on Submit event, 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()
    bool result=true;
    string strmsg="";
    System.Text.RegularExpressions.Regex reg = 
      new System.Text.RegularExpressions.Regex(RegularExpression);
    for(int i=0;i<objList.Count;i++)
        System.Text.RegularExpressions.MatchCollection  Mcol = 
        if(Mcol.Count<0 || !Mcol[0].Value.Equals(((TextBox)objList[i]).Text.Trim()))
    this.ErrorMessage = strmsg;

    return result;

Here your go... Build this control library, add reference to your project and enjoy validating.


  • Created on 10th 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

Questionquestion Pin
vadiraj hebbar13-Aug-10 5:21
membervadiraj hebbar13-Aug-10 5:21 
GeneralTake a look at RequiredTextBox control Pin
azamsharp12-May-09 8:18
memberazamsharp12-May-09 8:18 
GeneralAre you sure it can be compiled the source code Pin
wojtas00721-Dec-05 23:55
memberwojtas00721-Dec-05 23:55 

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
Web03 | 2.8.170813.1 | Last Updated 12 Oct 2004
Article Copyright 2004 by Gaurang Desai
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid