Coding Faster with dotNetTips Spargine: Validating Data Made Easy with Validator

Spargine is a collection of open-source assemblies and NuGet packages designed for .NET 10, which I have been developing and maintaining since the release of .NET Framework 2. These assemblies are not only a core part of my projects but are also actively deployed in production environments across several companies I collaborate with.

Get Spargine

You can access the source code and NuGet packages here:

Throughout my career as a software engineer, I have analyzed millions of lines of code and noticed a recurring issue: insufficient validation for data used in code. While it may seem like a minor concern, proper validation is crucial—bad input leads to bad output. If erroneous data makes its way into a database, fixing it can be a nightmare.

To address this, Spargine has always included helper methods for validation. In later versions, I have enhanced these methods to make data validation even more accessible. I hope that the .NET team at Microsoft considers incorporating similar helper methods into .NET in the future. Until then, teams can take advantage of the Validator class available in DotNetTips.Spargine.Core.

Effortless Data Validation

This article provides an overview of the available data validation methods, along with practical examples. For all methods, the throwException parameter can be set to true. If validation fails, the appropriate exception will be thrown. If a custom error message is not provided, a default message is used.

Validation Methods

Below are the core data validation methods available in Spargine’s Validator class:

  • CheckExists(bool createDirectory, bool throwException)
    Checks if the specified DirectoryInfo exists on the file system. Optionally creates the directory if it does not exist.
    Overloaded to work with FileInfo.
  • CheckIsCondition<T>(bool condition, in bool throwException)
    Validates whether a specified condition is true for the input value.
  • CheckIsDefined(bool throwException)
    Confirms that the specified enum value is defined within its enumeration type.
  • CheckIsInRange(DateTime lower, DateTime upper, in bool throwException)
    Verifies that the input value is within a specified range.
    Overloaded to support TimeOnly, DateOnly, int, long, double, decimal, and DateTimeOffset.
  • CheckIsNotEmpty<T>(bool throwException)
    Ensures that the ReadOnlySpan<T> is not empty.
    Overloaded to work with Guid.
  • CheckIsNotNull<T>(bool throwException)
    Validates that the input value is not null.
  • CheckIsNotNullOrEmpty(bool throwException = false)
    Checks whether the specified string is not null or empty.
  • CheckItemsExists<T>(bool throwException)
    Ensures that the input IEnumerable<T> contains items.
  • CheckTypeEquals(Type expectedType, in bool throwException)
    Ensures that the input type matches the expected type.

Methods in Action

Checking That a File Exists

Before attempting to work with a file on the system, use CheckExists() as shown below:

_ = file.CheckExists(throwException: true);

Validating Enums

One issue I rarely see developers handle is validating the value of an Enum. If an invalid number is passed, an exception will be thrown. Use CheckIsDefined() to prevent this issue:

if (searchOption.CheckIsDefined() is false)
{
    searchOption = SearchOption.TopDirectoryOnly;
}

Validating a Data Range

Values outside an expected range can cause issues. Use CheckIsInRange() to ensure input is within the specified boundaries:

var isValid = input.CheckIsInRange(0, 100);

Validating for Null Values

One of the most common exceptions in applications occurs when code attempts to call methods on a null value. I have seen these issues reach production and take down entire systems. To avoid this, use CheckIsNotNull():

if (args.CheckItemsExists() == false || format.CheckIsNotNull() == false)
{
    return ControlChars.EmptyString;
}

Conclusion

I use these Validator methods extensively to enforce data integrity and correctness in my applications. By incorporating these validation techniques, developers can write cleaner, safer, and more maintainable code.

For hundreds of additional examples, check out the Spargine source code.

Get Involved!

The success of open-source projects like Spargine relies on community contributions. If you find these updates useful or have ideas for further improvements, I encourage you to contribute by:

  • Submitting pull requests
  • Reporting issues
  • Suggesting new features

Your input is invaluable in making Spargine an even more powerful tool for the .NET community.

If you are interested in contributing or have any questions, feel free to contact me via email at dotnetdave@live.com. Your support and collaboration are greatly appreciated!

Thank you, and happy coding!

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copywritten and cannot be preproduced in any way without express permission from David McCarter.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.