Utility Functions

These functions can be used with any type when building validation functions.


ForEach

Adds a validator to validate all items in a collection from the target of the selector expression.

Method
ForEach<T, P>(Expression<Func<T, IEnumerable<P>>> selector, Action<IValidatorBuilder<P>> func)
Example Usage
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

Message

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.

Method
Message<T>(string message)
Message<T>(Func<ValidationContext<T>, string> func)
Example Usage

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)