Skip to main content
2 of 2
edited tags
Erik
  • 143
  • 8

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 < MinLength || code.Length > 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());
}
Erik
  • 143
  • 8