Keys and Messages

All built-in validation functions provide the ability to set the key of the value being validated and also customise the error message.

Keys and messages are set via optional parameters and are passed to the broken rules collection during validation.


Example Usage

Example setting the key.

var validator = new ValidatorBuilder<Employee>()
    .NotNull(key: "NullEmployee") // or .NotNull("NullEmployee")
    .Build();
    
var result = validator.Validate(null);
var brokenRule = result.BrokenRules.First();

Console.WriteLine($"[{rule.Rule}] {rule.Key}: {rule.Message}");

// output
// [NotNull] NullEmployee: Value cannot be null.

Example setting the message.

var validator = new ValidatorBuilder<Employee>()
    .Required(e => e.FirstName, message: "Please provide first name.")
    .Build();
    
var result = validator.Validate(new Employee { LastName = "Smithers" });
var brokenRule = result.BrokenRules.First();

Console.WriteLine($"[{rule.Rule}] {rule.Key}: {rule.Message}");

// output
// [Required] FirstName: Please provide first name.

Example setting key and message.

var validator = new ValidatorBuilder<Employee>()
    .Required(e => e.FirstName, "EmployeeFirstName", "Please provide first name.")
    .Build();
    
var result = validator.Validate(new Employee { LastName = "Smithers" });
var brokenRule = result.BrokenRules.First();

Console.WriteLine($"[{rule.Rule}] {rule.Key}: {rule.Message}");

// output
// [Required] EmployeeFirstName: Please provide first name.