Validatum provides built-in extension methods that allow for conditional execution of a validation function.
Executes a function when the predicate resolves to true.
Validation function is executed when predicate is true
var validator = new ValidatorBuilder<string>()
.When(
ctx => context.Value == "trap",
ctx =>
{
if (context.Value == "trap")
{
context.AddBrokenRule("ItsATrap", "Trapped", "You fell into my trap");
}
})
.Build();
// this will trigger the validation function to be executed
var result = validator.Validate("trap");
Validation function is not executed when predicate is false
var validator = new ValidatorBuilder<string>()
.When(
ctx => context.Value == "trap",
ctx =>
{
if (context.Value == "trap")
{
context.AddBrokenRule("ItsATrap", "Trapped", "You fell into my trap");
}
})
.Build();
// this will not trigger the validation function to be executed
var result = validator.Validate("sucker");
Executes a function when the predicate resolves to false.
Validation function is not executed when predicate is true
var validator = new ValidatorBuilder<string>()
.WhenNot(
ctx => context.Value == "trap",
ctx =>
{
if (context.Value == "trap")
{
context.AddBrokenRule("ItsATrap", "Trapped", "You fell into my trap");
}
})
.Build();
// this will not trigger the validation function to be executed
var result = validator.Validate("trap");
Validation function is executed when predicate is false
var validator = new ValidatorBuilder<string>()
.WhenNot(
ctx => context.Value == "trap",
ctx =>
{
if (context.Value == "trap")
{
context.AddBrokenRule("ItsATrap", "Trapped", "You fell into my trap");
}
})
.Build();
// this will trigger the validation function to be executed
var result = validator.Validate("sucker");
Allows for the inclusion of a new ValidatorBuilder<T> when the predicate resolves to true.
Validator is built and function is executed when predicate is true
var validator = new ValidatorBuilder<string>()
.If(ctx => context.Value == "howdy",
(builder) =>
{
builder
.NotNull()
.Contains("how"); // no need to call Build()
})
.Build();
// the conditional validator will be built and executed
var result = validator.Validate("howdy");
Allows for the inclusion of a new IValidatorBuilder<T> whenValidationContext<T>.IsValid resolves to true.
var validator = new ValidatorBuilder<Employee>()
.For(e => e.Age, v => v.GreaterThan(18))
// context.IsValid is true
.Continue((builder) =>
{
builder.For(e => e.DriversLicenceNo, v => v.NotNull());
})
// this will make context.IsValid be false
.For(e => e.DriversLicenceNo, v => v.Null())
// context.IsValid is now false, continue function won't execute
.Continue((builder) =>
{
builder.NotNull();
})
.Build();
var result = validator.Validate(new Employee { Age = 22, DriversLicenceNo = "A2345" });