In my MVC-App I want to create a method that will be used everywhere to avoid having any special characters like @, ", ' or anything else provoking a major problem.
So I'm trying to build this method using a regex that parses a string to detect if there's any special characters in the string and put a \ in front of them to make them harmless.
public static string ParseStringForSpecialChars(string stringToParse)
{
const string regexItem = "^[a-zA-Z0-9 ]*$";
string stringToReturn = Regex.Replace(stringToParse, regexItem, "\\");
return stringToReturn;
}
There are many problems in my code:
1) I am not familiar with regex and I have troubles figuring out what I wanted to do. Here, I think I was trying to detect if there were any characters other than thos in the regexItem; 2) When the code hits the string stringToReturn =
line, my app crashed as it says that the value cannot be null.
Can anyone help me out? Thanks!
EDIT
I have been asked to show an example of special characters, here they are:
'/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'
You get the idea, I just want to avoid sending a string to the database containing a ', because that will be interpreted as then end of a string and will provoke an error.