Files

46 lines
1.7 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Reflection;
namespace ArgumentsToolkit;
/// <summary>
/// Класс для выполнения валидации модели Options на основе атрибутов.
/// </summary>
public static class Validator
{
/// <summary>
/// Проверяет объект <paramref name="options"/> на соответствие правилам валидации.
/// </summary>
/// <typeparam name="T">Тип модели опций.</typeparam>
/// <param name="options">Экземпляр модели опций.</param>
/// <param name="errors">Список ошибок валидации.</param>
/// <returns>true, если ошибок нет; иначе false.</returns>
public static bool Validate<T>(T options, out string[] errors)
{
var list = new List<string>();
var props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var p in props)
{
// Проверяем только свойства с [Option]
var optionAttr = p.GetCustomAttribute<OptionAttribute>();
if (optionAttr == null) continue;
var val = p.GetValue(options);
// Берём все атрибуты, которые реализуют IValidationAttribute
foreach (var attr in p.GetCustomAttributes().OfType<ValidationAttribute>())
{
if (!attr.Validate(val))
{
var error = attr.GetErrorMessage(optionAttr.Name, val);
list.Add(error);
}
}
}
errors = list.ToArray();
return list.Count == 0;
}
}