When there are multiple invalid properties that are decorated with data annotations and validated with custom validation, I want to obtain validation results for all the invalid properties rather than just the first invalid one (as what is produced by the following code).
using MiniValidation;
using System.ComponentModel.DataAnnotations;
var widget = new Widget { Name = "A", Age = 0 };
if (!MiniValidator.TryValidate(widget, out var errors))
{
foreach (var entry in errors)
{
Console.WriteLine($" {entry.Key}:");
foreach (var error in entry.Value)
{
Console.WriteLine($" - {error}");
}
}
}
class Widget : IValidatableObject
{
[Required, MinLength(3)]
public string Name { get; set; } = null!;
public int Age { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext ctx)
{
if (Age < 10)
yield return new ValidationResult("Age cannot be less than 10.", [nameof(Age)]);
}
}
I don’t want to replace the attribute-based validations with custom validation.
class Widget : IValidatableObject
{
public string Name { get; set; } = null!;
public int Age { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext ctx)
{
if (Name is null)
yield return new ValidationResult("Name must be specified.", [nameof(Name)]);
if (Name?.Length < 3)
yield return new ValidationResult($"{Name} must contain at least 3 characters.", [nameof(Name)]);
if (Age < 10)
yield return new ValidationResult("Age cannot be less than 10.", [nameof(Age)]);
}
}