|
|
| Custom Regular Expression Validator
|
The normal
RegularExpressionValidator comes with default regular expressions items
as most common items need to be used in many cases, but what if we
want to add more or make our favorite regular expressions items.
I made some changes in the RegulerExpressionValidator control to accept adding
more expressions, actually I didn't built it from scratch, this control is
inherited from RegulerExpressionValidator control, I just added a new property
called CustomExpressions which contains Enum with the new expressions name.
Note that the default ValidationExpression property has a high priority, means
if you have value in ValidationExpression Property and one in CustomExpressions
property, the one in ValidationExpression will run.
below is the source code of the validator, you can change the values in the enum
and in OnInit method to write your favorite regular expressions, Good luck.
|
using
System;
using System.Web;
using
System.Collections;
using
System.ComponentModel;
using
System.Web.UI.WebControls;
using System.Web.UI;
using
System.Collections.Generic;
using System.Text;
namespace
CustomValidationControls
{
public class RegExpressionValidatorList : RegularExpressionValidator
{
[
Bindable(true),
Category("Behavior"),
DefaultValue(""),
Description("More Reqular Expressions for validation use")
]
public ValidatorColl CustomExpression
{
get
{
object
s = (object)ViewState["CustomExpression"];
return
(s == null) ? ValidatorColl.Empty : (ValidatorColl)s;
}
set
{
ViewState["CustomExpression"] = value;
}
}
protected
override void OnInit(EventArgs e)
{
base.OnInit(e);
if (ValidationExpression == string.Empty)
{
ValidatorColl
coll = CustomExpression;
switch (coll)
{
case ValidatorColl.Arabic:
this.ValidationExpression = "[^a-zA-Z]*";
break;
case
ValidatorColl.Numbers:
this.ValidationExpression = "^\\d*[0-9](|.\\d*[0-9]|,\\d*[0-9])?$";
break;
case
ValidatorColl.PositiveNumbers:
this.ValidationExpression =
"(^\\d*\\.?\\d*[1-9]+\\d*$)|(^[1-9]+\\d*\\.\\d*$)";
break;
case ValidatorColl.Empty:
this.ValidationExpression = string.Empty;
break;
}
}
}
}
public enum ValidatorColl
{
Arabic,
Numbers,
PositiveNumbers,
Empty
}
}
|
|
|
|
|
|