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.
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.
private System.Collections.ArrayList objList=
new System.Collections.ArrayList();
private System.Collections.ArrayList arrErrorMessage=
new System.Collections.ArrayList();
private int iAlertType=0;
Adding Method to Add Fields and Message to control
Create one function to add control and message to this 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.
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();
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.
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
.
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.