Click here to Skip to main content
15,878,814 members
Articles / Web Development / ASP.NET
Article

Combine RegularExpression Validation Control with RequiredField Validation Control

Rate me:
Please Sign up or sign in to vote.
3.12/5 (13 votes)
11 Oct 20042 min read 63.6K   979   29   3
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

Introduction

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.

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

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.

C#
/// 
/// 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:

C#
///
/// Add TextBox control and Display message to private ArrayList
/// 
public void AddControlToValidate(TextBox objCtl,string strErrorMessage)
{
  objList.Add(objCtl); 
  arrErrorMessage.Add(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.

C#
protected override void OnPreRender(EventArgs e)
{
    base.OnPreRender (e);
    if(objList.Count==0)
    {
        AddControlToValidate((TextBox)Page.FindControl(ControlToValidate), 
                                                               ErrorMessage);  
    }

    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(@"m=re.exec(document.all['"+ 
                              ((TextBox)objList[i]).ID+"'].value);");
        strJavaScript.Append(@"if( m == null || m[0]!=document.all['"
                             +((TextBox)objList[i]).ID+"'].value){");

        if(!blnRequired)
        {
            strJavaScript.Append(@"if(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
        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+"'].style.visibility='visible';document.all['"+
                 this.ID+"'].innerHTML=msg+'</ui>';alert(document.all['"+
                 this.ID+"'].visibility);return false;}"); 
    }
    strJavaScript.Append(@"return true;}</script>");
    Page.RegisterClientScriptBlock("funRegValidate",strJavaScript.ToString());

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.

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()
{
    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 = 
                      reg.Matches(((TextBox)objList[i]).Text.Trim());
        if(Mcol.Count<0 || !Mcol[0].Value.Equals(((TextBox)objList[i]).Text.Trim()))
        {
            strmsg+="<br>"+(string)arrErrorMessage[i];
            result=false;
        }
    }
    this.ErrorMessage = strmsg;

    return result;
}

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

History

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

 
Questionquestion Pin
vadiraj hebbar13-Aug-10 5:21
vadiraj hebbar13-Aug-10 5:21 
GeneralTake a look at RequiredTextBox control Pin
azamsharp12-May-09 8:18
azamsharp12-May-09 8:18 
GeneralAre you sure it can be compiled the source code Pin
wojtas00721-Dec-05 23:55
wojtas00721-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.