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());
}
1 Answer 1
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.
-
\$\begingroup\$ @Erik Notice the
^
at the beginning of the regex. It negates the meaning - that is, it builds a blacklist from your whitelist, and the regex returns Success if the string has at least one blacklisted symbol. \$\endgroup\$vnp– vnp2015年11月18日 20:42:17 +00:00Commented Nov 18, 2015 at 20:42 -
\$\begingroup\$ I ended up using a modified version of your code and renamed the variable
ReferralCodeValidator
toReferralCodeBlackList
. Here is the relevant code:return !ReferralCodeBlackList.IsMatch(code);
\$\endgroup\$Erik– Erik2015年11月18日 21:21:40 +00:00Commented Nov 18, 2015 at 21:21
Explore related questions
See similar questions with these tags.