1

Suppose I have a group of unwanted characters & " > < { } ( ) and I want to validate that a given string does not contains those characters, for now I wrote function like:

bool IsStringValid(string s){
  if(s.Contains("&")| s.Contains(">")...)
    return false;
return true;
}

How can I write it more elegant? for example in regex?

Alex P
  • 12,249
  • 5
  • 51
  • 70
Plompy
  • 359
  • 3
  • 11

2 Answers2

2

Regex is always your friend.

Regex validationRegex = new Regex(@"^[^&""><{}\(\)]*$");

bool IsStringValid(string s) => validationRegex.IsMatch(s);
V0ldek
  • 9,623
  • 1
  • 26
  • 57
2
bool isValid =  !Regex.IsMatch(input, "[&\"><{}()]+");

But however I recommand you do it without regex:

bool isValid = !"&\"><{}()".Any(c=> input.Contains(c));
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171