This library aims at making validation easy, fluent and versatile.
Use this type of validation anywhere in your code. Just called the GetValidator()
on any object and start chaining your validation.
Create an ad-hoc validator class inheriting from CustomMonkeyValidatorBase<T>
and build your validator in the abstract SetupValidator()
method.
validators can be chained, and the validation will pickup all errors before throwing.
You can use an if/else if/else logic for more complex scenarios
If you want to break the validation if a certain condition is met, you can use the FailFastIf()
extension, which will throw immediatelly if the predicate returns false.
If you want to insert your own logic on validation failure, you can use the overload that takes an Action<List<string>>
where List<string>
are the validation errors.
You can set the optional throwMonkeyException
flag to true
if you just want to add some logic before the default exception is thrown.
For on the fly, one time only custom rules, you can simply chain a CustomRule()
and pass in your predicate.
For rules you want to reuse, but are not specific enough to put on a Validator class, I'd recommend creating a static class to extend the MonkeyValidator<T>
with your rule fragments:
which you can then chain to your other validators.
Sometimes, validation can hinder testability. A complex validator can become rather troublesome for testers, especially for testing edge cases where the validation has little to no bearing to the section of code being tested.
We can circumvent the issue by creating an injectable service like so:
This has the added advantage that if we need to inject other services that are required to fulfil our validation, those are encapsulated in the IStringValidator, and thus not required when unit testing. The IStringValidator can then be reused to add all the validation methods related to strings.