CodeSOD: Validly Numeric

Writing validation rules is one of the more tedious tasks a developer might need to do. Like testing code, it's all about finding edge cases, checking boundaries, and being exhaustive in your search for invalid data. Garbage in, garbage out, and validation filters the garbage.

But you might also be a bit too thorough. Kevin found this validation rule in his C# codebase:

RuleFor((p) => p.Quantity) .NotNull(); RuleFor((p) => p.Quantity.ToString()) .Matches(@"^[\d]+$").WithMessage("Must be a number.");

The ToString call should make you a bit suspicious, and that's a valid suspicion: p.Quantity is defined as a non-nullable integer. This code takes a value that can't be null by definition, and confirms that it isn't. Then it takes something that's definitely a number, converts it to a string, and verifies that the string holds a number. And even the regex is more complex than it strictly needs to be, thanks to the [].

I assume these validation rules also check to see that booleans are either true or false or FILE_NOT_FOUND.

[Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today!

This post originally appeared on The Daily WTF.

Leave a Reply

Your email address will not be published.