custom validator: IsNotNullOrEmptyOrWhitespace

Dec 1, 2011 at 4:08 PM

The Conditions library has a "IsNotNullOrWhitespace()" validator, but I improved on it somewhat.

      public static ConditionValidator<string> IsNotNullOrEmptyOrWhitespace(this ConditionValidator<string> validator)
{ // Value, ArgumentName and ThrowException won't show up in the IntelliSense dropdown list, but you can use them. if (string.IsNullOrWhiteSpace(validator.Value))
{ validator.ThrowException(validator.ArgumentName + " should not be null, empty or only whitespace"); } return validator; }

I gave it a more descriptive name that includes "OrEmpty". I know the framework uses "IsNotNullOrWhitespace", but it always confuses me whether it checks for all three conditions, and I need to read the docs each time. My name makes the validator's intent very clear.

Also, the library does a char-by-char check, whereas the version above defers to the framework to choose the algorithm. That way you get the same performance as you'd get from the framework--it actually may be the same today, but if the framework's implementation improves, then so will this method's.

To use the above, declare it in a "namespace CuttingEdge.Conditions { ... }".

Hope it helps.

Dec 1, 2011 at 6:46 PM

I must admit I find the IsNullOrWhiteSpace name not intuitive, but I decided to stick to that name in Conditions. Choosing the same name is less confusing, because now developers could at least expect the method to behave the same as the String.IsNullOrWhiteSpace method of the framework.

The String.IsNullOrWhiteSpace method is new in .NET 4.0, but CuttingEdge.Conditions is for .NET 2.0 and up and therefore cannot take a dependency on .NET 4.0 functionality. That's why it does the char-by-char check itself, instead of depending on String.IsNullOrWhiteSpace. I don't really think that the framework's implementation will ever be much faster than it currently is, so I don't think that's something you should really worry about. If you worry about that kind of optimizations, perhaps using CuttingEdge.Conditions isn't a wise thing in the first place ;-).



Dec 1, 2011 at 7:00 PM

Not use it! Why, I thought it was cutting edge?

Good point re versioning.

Dec 1, 2011 at 7:07 PM

Hehe.. you got me, it isn't cutting edge ;-).

I want Conditions to stay backward compatible for some time, or until there is a strong reason to go to .NET 4.0. But the IsNullOrWhiteSpace method alone doesn't seem like a valid reason to force a dependency on 4.0.