Friday, June 12, 2009

Validation - RegularExpression

Validation:
.Net inbuilt validation control custmaization
1)Create .cs class
#region LoadREVforLongText1
public RegularExpressionValidator LoadREVforLongText1(string controlName, string errorMsg, bool isValidationSummary, string valGroup)
{
RegularExpressionValidator revControl = new RegularExpressionValidator();
revControl.ValidationGroup = valGroup;
revControl.ControlToValidate = controlName;
revControl.ValidationExpression = @"(?!.*?\b\w{31,}).*";
revControl.ErrorMessage = "Please enter " + errorMsg + " words length max 30";

if (isValidationSummary == true)
{
revControl.Display = ValidatorDisplay.None;
}

return revControl;
}
#endregion

2)Create a instance for the class on .aspx.cs/.ascx.cs
ValidationControls vc = new ValidationControls();
protected void RegisterValidationControls()
{
RegularExpressionValidator revFullName = vc.LoadREVforLongText1 ("txtFullName", "full name", true, "2");
div_fullname.Controls.Add(revFullName);
}
3)call the above method on the page load event.

4)validating text should have div block. where the error message will display.

5)Need's to put validation summary in design page. set the properties ValidationGroup="2" DisplayMode="List"

Regular Expression:
for Phone no:
= @"^[\(\)\{\}\[\] a-zA-Z0-9''+,-]{0,100}$"
for Email with hypen
= @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$";
for Email without hypen
= @"^([0-9a-zA-Z]([.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$";
for Long text without space
= @"(?!.*?\b\w{31,}).*";

#region is Valid word
public bool isValid(string strText, int maxchars)
{
if (strText.Trim().Length > 0)
{
strText = strText.Trim();

string[] strLines = strText.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
int cnt = 0;
for (int i = 0; i < strLines.Length; i++)
{
string[] strWords = strLines[i].Split(' ');
cnt += strWords.Length;
for (int j = 0; j < strWords.Length; j++)
{
if (strWords[j].Length > maxchars)
{
return false;
}
}
}
}
return true;
}
#endregion

Copyright © 2009 Angel