These functions can be used with any type when building validation functions.
Adds a validator to validate all items in a collection from the target of the selector expression.
var validator = new ValidatorBuilder<Employee>()
.ForEach(
e => e.Skills,
builder =>
{
builder.NotNull().MinLength(3);
})
.Build();
// this will produce two broken rules
var result = validator.Validate(new Employee
{
Skills = new[] { "Dev", "No", "Junk", null }
});
foreach (var rule in result.BrokenRules)
{
Console.WriteLine($"[{rule.Rule}] {rule.Key} {rule.Message}")
}
// output
// [MinLength] e.Skills[1] Value must have minimum length of 3
// [NotNull] e.Skills[3] Value cannot be null
Aggregates broken rules into a single broken rule with the specified message. This function should be added last and only once to the builder to avoid strange results.
Using message string
var validator = new ValidatorBuilder<string>()
.StartsWith("d")
.EndsWith("m")
.Email()
.Message("This is not a drum")
.Build();
// this will produce two broken rules (StartsWith,Email)
var result = validator.Validate("everything is a drum");
foreach (var rule in result.BrokenRules)
{
Console.WriteLine($"[{rule.Rule}]: {rule.Message}")
}
// output
// [StartsWith,Email]: This is not a drum
Using function returning string
var validator = new ValidatorBuilder<string>()
.StartsWith("d")
.EndsWith("m")
.Email()
// access the context to build the message
.Message(ctx => $"This is not a drum ({ctx.BrokenRules.Count})")
.Build();
// this will produce two broken rules (StartsWith,Email)
var result = validator.Validate("everything is a drum");
foreach (var rule in result.BrokenRules)
{
Console.WriteLine($"[{rule.Rule}]: {rule.Message}")
}
// output
// [StartsWith,Email]: This is not a drum (2)