You can use the CleanInput method defined in this example to strip potentially harmful characters that have been entered into a text field that accepts user input. In this case, CleanInput strips out all non-alphanumeric characters except periods (.), at symbols (@), and hyphens (-), and returns the remaining string.
using System;
using System.Text.RegularExpressions;
public class Example
{
protected static string CleanInput (string strIn)
{
// Replace invalid characters with empty strings.
try
{
return System.Text.RegularExpressions.Regex.Replace(strIn, @"[^w.@ -]", "",
RegexOptions.None, TimeSpan.FromSeconds(1.5));
}
// If we timeout when replacing invalid characters,
// we should return Empty.
catch (System.Text.RegularExpressions.RegexMatchTimeoutException)
{
return String.Empty;
}
}
}
Reference: http://msdn.microsoft.com/en-us/library/844skk0h(v=vs.110).aspx
Originally Posted on April 4, 2014
Last Updated on October 26, 2015
Last Updated on October 26, 2015
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.