Код: Выделить всё
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 Validate(ValidationContext ctx)
{
if (Age < 10)
yield return new ValidationResult("Age cannot be less than 10.", [nameof(Age)]);
}
}

Я не хочу заменять проверки на основе атрибутов пользовательской проверкой.
Код: Выделить всё
class Widget : IValidatableObject
{
public string Name { get; set; } = null!;
public int Age { get; set; }
public IEnumerable 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)]);
}
}

Подробнее здесь: https://stackoverflow.com/questions/788 ... ones-for-c