Variable length string validation against whitelisted characters I need to validate a variable length string against some white-listed characters. The algorithm that I have works but I have a sneaking suspicion that there is a more elegant solution. The code below hasn't been identified as a bottleneck so ease of maintenance is preferred over a clever but confusing implementation.

private static readonly Regex ReferralCodeValidator = new Regex(
   @"[ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789]",
   RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);

private const int MinLength = 3;

private const int MaxLength = 8;

public static bool IsValidReferralCode(this string code)
{
   if (string.IsNullOrWhiteSpace(code))
   {
       return false;
   }

   if (code.Length &lt; MinLength || code.Length &gt; MaxLength)
   {
       return false;
   }

   // Variable for clarity and easier regex troubleshooting
   var strippedCode = ReferralCodeValidator.Replace(code, string.Empty);
   return strippedCode == string.Empty;
}


I also have the following NUnit tests to validate/exercise the solution:

[Test]
[TestCase("AARPeVER", true)]
[TestCase("1234EVE", true)]
[TestCase(null, false)]
[TestCase("AARP", true)]
[TestCase("AA", false)]
[TestCase("AAr", true)]
[TestCase("123456789", false)]
[TestCase("AARP0", false, Description = "Zero isn't allowed.")]
[TestCase("AARPO", true, Description = "The letter O is allowed.")]
[TestCase("", false)]
[TestCase("  ", false)]
[TestCase("AAR ", false)]
[TestCase("AAR\n", false)]
[TestCase("Ever||12", false)]
public void IsValidReferralCode(string input, bool success)
{
    Assert.AreEqual(success, input.IsValidReferralCode());
}
Instead of removing valid characters, you may look for invalid ones:

    private static readonly Regex ReferralCodeValidator = new Regex(
       @"[^ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789]",
       RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);

    public static bool IsValidReferralCode(this string code)
    {
        // preliminary tests omitted for brevity
        return !ReferralCodeValidator.Match(code).Success;
    }


I can't say if this solution is more elegant (beauty is in the eye of beholder), but it surely looks more straightforward.