Tuesday, January 22, 2013

How to filter special characters from user input?

I am using a textbox to capture user entry to create a custom SQL select statement. I have everything working fine but I get an exception thrown when I wanted to search by city name and I entered, "Cox's Bazar" in the textbox.
In this case you need to filter special characters from user input values that produce this error. You can filter user inputs using following method in your string helper class:

        /// <summary>
        /// Replace UnWanted Character from string
        /// </summary>
        /// <param name="input">Input string</param>
        /// <returns></returns>
        public static string ReplaceUnWantedCharacter(string input)
            input = input.Replace('+', ',');
            input = input.Replace("--", "++");
            input = input.Replace('&', ',');
            input = input.Replace("%", "[%]");
            input = input.Replace("_", "[_]");
            input = input.Replace("[", "[[]");
            input = input.Replace("]", "[]]");
            input = input.Replace("'", "''");
                        return input;

the use of this method may be like:
string cityName = StringHelper.ReplaceUnWantedCharacter(txtCityName.Text.Trim());

No comments:

Post a Comment