Sanitizing input
Sometimes, you will need to sanitize input. This could be to prevent SQL injections or ensure that an entered URL is valid. In this recipe, we will look at replacing the bad words in a string with asterisks. We are sure that there are more elegant and code-efficient methods of writing sanitation logic using regex (especially when we have a large collection of blacklist words), but we want to illustrate a concept here.
Getting ready
Ensure that you have added the correct assembly to your class. At the top of your code file, add the following line of code if you haven't done so already:
using System.Text.RegularExpressions;
How to do it…
Create a new method in your
Recipes.cs
class calledSanitizeInput()
and let it accept a string parameter:public string SanitizeInput(string input) { }
Add a list of type
List<string>
to the method that contains the bad words we want to remove from the input:List<string> lstBad = new List<string>(new string[] {...