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,086
  • 5
  • 50
  • 67
Plompy
  • 339
  • 2
  • 10

2 Answers2

2

Regex is always your friend.

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

bool IsStringValid(string s) => validationRegex.IsMatch(s);
V0ldek
  • 8,822
  • 23
  • 48
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
  • 32,319
  • 30
  • 98
  • 161