How to ensure a string only contains allowable characters

This was inspired by this question on Stack Overflow.  There are probably a lot of ways to skin this cat, but I hope to show a very straight forward one.  Let’s assume you only want to allow the following character: +, -, (, and ).  Let’s also assume that digits and space are valid because we’re going to validate a phone number.  Then let’s assume the following strings: (123) 456-7890 and (123) 456/7890.

Well, the code to do that might look like this:

var allowedChars = new List<char> { '+', '-', '(', ')' }
if (input.Any(c => !(char.IsDigit(c) ||
    char.IsWhiteSpace(c) ||
    // this is an invalid string

This code is going to iterate through every character in the string, and if it’s **not** a digit, white space, or allowed character, it will return true and thus it’s an invalid string.

In our example, the first string would pass and the second would fail.

Until next time, happy coding!

One thought on “How to ensure a string only contains allowable characters

  1. Nice (simple) solution to that poster’s question. Someone can come back 6 months later and immediately tell what’s it’s doing too. Regex is just a pain unless it really fits the requirements… and even then.

    I think that last check needs a correction though:
    || !allowedChars.Contains(c)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>