Check if string contains non-alphanumeric except underscore

3.1k views Asked by At

I'm trying to write in if statement that runs if a string contains any non-alpahnumeric character with the exception of an underscore.

This is what I have and I'm trying to figure a simple way to add the exception for underscore but I'm having difficulty. (where key is a string).

// Check for non-alphanumerics except underscore
if (!(key.All(char.IsLetterOrDigit)))                                        
{
    validationResult = false;
}
1

There are 1 answers

1
Damien_The_Unbeliever On BEST ANSWER

You just need to extend the logic within the All:

if (!(key.All(c => char.IsLetterOrDigit(c) || c=='_')))