Regular expressions are a good way to validate text fields such as names, addresses, phone numbers, and other user information. To validate input captured with server controls, you can use the RegularExpressionValidator control.
To validate other forms of input, such as query strings, cookies, and HTML control input, you can use the System.Text.RegularExpressions.Regex class.
Using the Regex Class
1)Add a using statement to reference the System.Text.RegularExpressions namespace.
2)Call the IsMatch method of the Regex class, as shown in the following example.
// Instance method:
Regex reg = new Regex(@"^[a-zA-Z'.]{1,40}$");
Response.Write(reg.IsMatch(txtName.Text));
// Static method:
if (!Regex.IsMatch(txtName.Text, @"^[a-zA-Z'.]{1,40}$"))
{
}
Regex regex = new Regex(@"
^ # anchor at the start
(?=.*\d) # must contain at least one numeric character
(?=.*[a-z]) # must contain one lowercase character
(?=.*[A-Z]) # must contain one uppercase character
.{8,10} # From 8 to 10 characters in length
\s # allows a space
$ # anchor at the end",
RegexOptions.IgnorePatternWhitespace);
Trimming a String
string initialText = “abc-12-xyz-786″;
System.Text.RegularExpressions.Regex noNumbers = new System.Text.RegularExpressions.Regex (@”\D”);
String numbersOnly = noNumbers.Replace (initialText, String.Empty);
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment