ValidationKit 8.6.4
dotnet add package ValidationKit --version 8.6.4
NuGet\Install-Package ValidationKit -Version 8.6.4
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="ValidationKit" Version="8.6.4" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ValidationKit" Version="8.6.4" />
<PackageReference Include="ValidationKit" />
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add ValidationKit --version 8.6.4
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: ValidationKit, 8.6.4"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package ValidationKit@8.6.4
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=ValidationKit&version=8.6.4
#tool nuget:?package=ValidationKit&version=8.6.4
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
ValidationKit
Fluent-валидатор для .NET 8. Проверяет свойства любого объекта по имени строкой, без лямбда-выражений. Цепочка правил читается как текст.
Установка
dotnet add package ValidationKit
API
Класс Validator
Создание и запуск
| Метод | Описание |
|---|---|
static Validator Check(object target) |
Создать валидатор для объекта |
static bool IsValid(object target) |
Быстрая проверка -- есть ли ошибки (без правил проверяет пустоту) |
List<ValidationError> Validate() |
Выполнить все проверки и получить список ошибок. Пустой список = нет ошибок. |
Правила валидации
| Метод | Описание |
|---|---|
Required(string property, string? message) |
Обязательное поле (не null и не пустая строка) |
MinLength(string property, int min, string? message) |
Минимальная длина строки |
MaxLength(string property, int max, string? message) |
Максимальная длина строки |
Email(string property, string? message) |
Корректный email-адрес |
Phone(string property, string? message) |
Корректный номер телефона |
Range(string property, double min, double max, string? message) |
Число в диапазоне |
Min(string property, double min, string? message) |
Число не меньше указанного |
Max(string property, double max, string? message) |
Число не больше указанного |
GreaterThan(string property, double value, string? message) |
Число строго больше указанного |
LessThan(string property, double value, string? message) |
Число строго меньше указанного |
Match(string property, string pattern, string? message) |
Соответствие регулярному выражению |
Equal(string property1, string property2, string? message) |
Два свойства имеют одинаковое значение |
Date(string property, string? message) |
Строка содержит корректную дату |
Url(string property, string? message) |
Строка содержит корректный URL (http/https) |
When(string property, object expectedValue, Action<Validator> configure) |
Условная валидация -- правила выполняются только если свойство равно ожидаемому значению |
Custom(string property, Func<object?, bool> predicate, string? message) |
Пользовательская проверка через функцию |
Класс ValidationError
| Свойство | Тип | Описание |
|---|---|---|
Property |
string |
Имя свойства, не прошедшего валидацию |
Message |
string |
Сообщение об ошибке |
Примеры
Пример 1: Регистрация пользователя
using ValidationKit;
var user = new {
Login = "admin",
Email = "test@mail.ru",
Password = "123",
PasswordConfirm = "1234",
Age = 15
};
var errors = Validator.Check(user)
.Required("Login", "Введите логин")
.MinLength("Login", 3, "Логин минимум 3 символа")
.MaxLength("Login", 20)
.Email("Email")
.Required("Password")
.MinLength("Password", 6, "Пароль минимум 6 символов")
.Equal("Password", "PasswordConfirm", "Пароли не совпадают")
.Range("Age", 18, 100, "Возраст от 18 до 100")
.Validate();
foreach (var err in errors)
Console.WriteLine($"{err.Property}: {err.Message}");
// Password: Пароль минимум 6 символов
// Password: Пароли не совпадают
// Age: Возраст от 18 до 100
Пример 2: Валидация товара с условной проверкой
var product = new {
Name = "",
Price = -5,
Category = "Электроника",
Warranty = 0,
Website = "not-a-url"
};
var errors = Validator.Check(product)
.Required("Name", "Укажите название товара")
.GreaterThan("Price", 0, "Цена должна быть положительной")
.Url("Website", "Укажите корректный URL сайта")
.When("Category", "Электроника", v => v
.GreaterThan("Warranty", 0, "Для электроники гарантия обязательна")
)
.Validate();
// Name: Укажите название товара
// Price: Цена должна быть положительной
// Website: Укажите корректный URL сайта
// Warranty: Для электроники гарантия обязательна
Пример 3: Быстрая проверка и пользовательские правила
var order = new {
OrderDate = "2025-01-15",
DeliveryDate = "не дата",
Total = 500,
PromoCode = "SALE2025"
};
var errors = Validator.Check(order)
.Date("OrderDate")
.Date("DeliveryDate", "Некорректная дата доставки")
.LessThan("Total", 1000000, "Сумма не может превышать 1 000 000")
.Match("PromoCode", @"^[A-Z0-9]+$", "Промокод: только заглавные латинские и цифры")
.Custom("Total", val => (double)(int)val! > 0, "Сумма должна быть положительной")
.Validate();
// Быстрая проверка без деталей
bool isValid = Validator.IsValid(order);
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
net8.0
- No dependencies.
NuGet packages (1)
Showing the top 1 NuGet packages that depend on ValidationKit:
| Package | Downloads |
|---|---|
|
ISBuilder
Information System Builder — full toolkit for building .NET 8 WinForms applications with EF Core, SQL Server. Export, CRUD, forms, charts, auth, reports, validation, themes. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 8.6.4 | 136 | 4/12/2026 |