FluentValidation Library Overview. Part 7.2. Built-in Validators

← Previous part

*When writing this article, .NET 8/C# 12 were used.

This is another article on the library review FluentValidation in Russian. The source of information is the official documentation. I can't call this a lesson or a full translation, I decided to call it reviews. Here you can sometimes see things that are not described in the official documentation, as well as more detailed examples.

FluentValidation – This .NET a library for describing strongly typed data validation rules in the form of a fluid syntax, and their subsequent application. The library is flexible enough to build supported validations of any complexity.

In this section we will consider the following validators (5):

  • Length — the length of the string in the specified range or exact.

  • MaximumLength — maximum line length.

  • MinimumLength — minimum line length.

  • LessThan — less than a value whose type implements the interface IComparable.

  • LessThanOrEqualTo — less than or equal to a value whose type implements the interface IComparable.

List of all built-in validators (22):

Important! The code examples below are self-contained, it is enough to create a console application on .NET 8/C# 12 and connect there NuGet plastic bag FluentValidation 11.9.2 versions and just copy-paste the entire code into Program.cs for self-checking.

Length validator.

To the list of validators

Description:

Ensures that the length of the string (type string) is within the range of two integer values ​​(minimum number of characters and maximum number of characters) or is exactly equal to the specified integer value (specific number of characters).

Validator source code.

Code examples:

Let's check that the length of the string is within the range of two integer values ​​(minimum number of characters and maximum number of characters).

// Сигнатура перегруженного метода валидатора
public static IRuleBuilderOptions<T, string> Length<T>(
    this IRuleBuilder<T, string> ruleBuilder,
    int min,
    int max
)
// Пример кода
using FluentValidation;
using FluentValidation.Results;

// Создаём модель и заполняем данными
Request request = new()
{
    Input = "someinput", // Длина 9 символов
};
// Создаём валидатор
RequestValidator validator = new();

// Валидируем модель, получаем результат
ValidationResult validationResult = validator.Validate(request);

// Валидация успешно пройдена?
if (validationResult.IsValid)
    Console.WriteLine("Валидация пройдена успешно!");
else
    // Выводим ошибки на консоль, разделяя символом |
    Console.WriteLine(validationResult.ToString("|"));

// Не даём закрыться консоли
Console.ReadLine();

/// <summary>
/// Модель для валидатора <see cref="RequestValidator"/>
/// </summary>
internal record Request
{
    /// <summary>
    /// Валидируемое свойство
    /// </summary>
    public required string Input { get; init; }
}

/// <summary>
/// Валидатор для модели <see cref="Request"/>
/// </summary>
internal class RequestValidator : AbstractValidator<Request>
{
    public RequestValidator()
    {
        // Длина строки должна быть от 8 до 10 символов включительно
        RuleFor(request => request.Input).Length(8, 10);
    }
}

Let's check that the string length is within the range of two integer property values ​​(minimum number of characters and maximum number of characters):

// Сигнатура перегруженного метода валидатора
public static IRuleBuilderOptions<T, string> Length<T>(
    this IRuleBuilder<T, string> ruleBuilder,
    Func<T, int> min,
    Func<T, int> max
)
// Пример кода
using FluentValidation;
using FluentValidation.Results;

// Создаём модель и заполняем данными
Request request = new()
{
    LengthFrom = 8, // Свойство используется в валидаторе (Длина "От")
    Input = "someinput", // Длина 9 символов
    LengthTo = 10, // Свойство используется в валидаторе (Длина "До")
};
// Создаём валидатор
RequestValidator validator = new();

// Валидируем модель, получаем результат
ValidationResult validationResult = validator.Validate(request);

// Валидация успешно пройдена?
if (validationResult.IsValid)
    Console.WriteLine("Валидация пройдена успешно!");
else
    // Выводим ошибки на консоль, разделяя символом |
    Console.WriteLine(validationResult.ToString("|"));

Console.ReadLine();

/// <summary>
/// Модель для валидатора <see cref="RequestValidator"/>
/// </summary>
internal record Request
{
    /// <summary>
    /// Длина "От"
    /// </summary>
    public required int LengthFrom { get; init; }
    /// <summary>
    /// Валидируемое свойство
    /// </summary>
    public required string Input { get; init; }
    /// <summary>
    /// Длина "До"
    /// </summary>
    public required int LengthTo { get; init; }
}

/// <summary>
/// Валидатор для модели <see cref="Request"/>
/// </summary>
internal class RequestValidator : AbstractValidator<Request>
{
    public RequestValidator()
    {
        // Длина строки должна быть от 8 до 10 символов включительно
        RuleFor(request => request.Input)
            .Length(request => request.LengthFrom, request => request.LengthTo);
    }
}

Let's check that the length of the string is equal to an integer value (a specific number of characters):

// Сигнатура перегруженного метода валидатора
public static IRuleBuilderOptions<T, string> Length<T>(
    this IRuleBuilder<T, string> ruleBuilder,
    int exactLength
)
// Пример кода
using FluentValidation;
using FluentValidation.Results;

// Создаём модель и заполняем данными
Request request = new()
{
    Input = "someinput", // Длина 9 символов
};
// Создаём валидатор
RequestValidator validator = new();

// Валидируем модель, получаем результат
ValidationResult validationResult = validator.Validate(request);

// Валидация успешно пройдена?
if (validationResult.IsValid)
    Console.WriteLine("Валидация пройдена успешно!");
else
    // Выводим ошибки на консоль, разделяя символом |
    Console.WriteLine(validationResult.ToString("|"));

Console.ReadLine();

/// <summary>
/// Модель для валидатора <see cref="RequestValidator"/>
/// </summary>
internal record Request
{
    /// <summary>
    /// Валидируемое свойство
    /// </summary>
    public required string Input { get; init; }
}

/// <summary>
/// Валидатор для модели <see cref="Request"/>
/// </summary>
internal class RequestValidator : AbstractValidator<Request>
{
    public RequestValidator()
    {
        // Длина строки должна быть равна 9-ти символам
        RuleFor(request => request.Input).Length(9);
    }
}

Let's check that the length of the string is equal to the integer value of the property (a specific number of characters):

// Сигнатура перегруженного метода валидатора
public static IRuleBuilderOptions<T, string> Length<T>(
    this IRuleBuilder<T, string> ruleBuilder,
    Func<T, int> exactLength
)
// Пример кода
using FluentValidation;
using FluentValidation.Results;

// Создаём модель и заполняем данными
Request request = new()
{
    ExactlyLength = 9, // Свойство используется в валидаторе (Точная длина)
    Input = "someinput", // Длина 9 символов
};
// Создаём валидатор
RequestValidator validator = new();

// Валидируем модель, получаем результат
ValidationResult validationResult = validator.Validate(request);

// Валидация успешно пройдена?
if (validationResult.IsValid)
    Console.WriteLine("Валидация пройдена успешно!");
else
    // Выводим ошибки на консоль, разделяя символом |
    Console.WriteLine(validationResult.ToString("|"));

Console.ReadLine();

/// <summary>
/// Модель для валидатора <see cref="RequestValidator"/>
/// </summary>
internal record Request
{
    /// <summary>
    /// Валидируемое свойство
    /// </summary>
    public required string Input { get; init; }
    /// <summary>
    /// Точная длина
    /// </summary>
    public required int ExactlyLength { get; init; }
}

/// <summary>
/// Валидатор для модели <see cref="Request"/>
/// </summary>
internal class RequestValidator : AbstractValidator<Request>
{
    public RequestValidator()
    {
        // Длина строки должна быть равна 9-ти символам
        RuleFor(request => request.Input)
            .Length(request => request.ExactlyLength);
    }
}

Examples of errors:

// Когда указываем диапазон
'Input' должно быть длиной от 8 до 10 символов. Количество введенных символов: 11.
// Когда указываем точное значение
'Input' должно быть длиной 10 символа(ов). Количество введенных символов: 9.

Available placeholders:

{PropertyName} — name of the property being validated

{PropertyValue} — value of the property being validated

{PropertyPath} — full path to the property

{MinLength} — minimum length

{MaxLength} — maximum length

{TotalLength} — the length of the string value being checked

Example code with placeholders 1 (range):

using FluentValidation;
using FluentValidation.Results;

// Создаём модель и заполняем данными
Request request = new()
{
    Input = "someinputtt", // Длина 11 символов
};
// Создаём валидатор
RequestValidator validator = new();

// Валидируем модель, получаем результат
ValidationResult validationResult = validator.Validate(request);

// Валидация успешно пройдена?
if (validationResult.IsValid)
    Console.WriteLine("Валидация пройдена успешно!");
else
    // Выводим ошибки на консоль, разделяя символом |
    Console.WriteLine(validationResult.ToString("|"));

Console.ReadLine();

/// <summary>
/// Модель для валидатора <see cref="RequestValidator"/>
/// </summary>
internal record Request
{
    /// <summary>
    /// Валидируемое свойство
    /// </summary>
    public required string Input { get; init; }
}

/// <summary>
/// Валидатор для модели <see cref="Request"/>
/// </summary>
internal class RequestValidator : AbstractValidator<Request>
{
    public RequestValidator()
    {
        // Длина строки должна быть от 8 до 10 символов включительно
        RuleFor(request => request.Input)
            .Length(8, 10)
                .WithMessage("""
                             PropertyName: {PropertyName}
                             PropertyValue: {PropertyValue}
                             PropertyPath: {PropertyPath}
                             MinLength: {MinLength}
                             MaxLength: {MaxLength}
                             TotalLength: {TotalLength}
                             """);
    }
}

Example of error with placeholders 1 (range):

PropertyName: Input
PropertyValue: someinputtt
PropertyPath: Input
MinLength: 8
MaxLength: 10
TotalLength: 11

Example code with 2 placeholders (exact value):

using FluentValidation;
using FluentValidation.Results;

// Создаём модель и заполняем данными
Request request = new()
{
    Input = "someinputtt", // Длина 11 символов
};
// Создаём валидатор
RequestValidator validator = new();

// Валидируем модель, получаем результат
ValidationResult validationResult = validator.Validate(request);

// Валидация успешно пройдена?
if (validationResult.IsValid)
    Console.WriteLine("Валидация пройдена успешно!");
else
    // Выводим ошибки на консоль, разделяя символом |
    Console.WriteLine(validationResult.ToString("|"));

Console.ReadLine();

/// <summary>
/// Модель для валидатора <see cref="RequestValidator"/>
/// </summary>
internal record Request
{
    /// <summary>
    /// Валидируемое свойство
    /// </summary>
    public required string Input { get; init; }
}

/// <summary>
/// Валидатор для модели <see cref="Request"/>
/// </summary>
internal class RequestValidator : AbstractValidator<Request>
{
    public RequestValidator()
    {
        // Длина строки должна быть равна 8-ми символам
        RuleFor(request => request.Input)
            .Length(8)
                .WithMessage("""
                             PropertyName: {PropertyName}
                             PropertyValue: {PropertyValue}
                             PropertyPath: {PropertyPath}
                             MinLength: {MinLength}
                             MaxLength: {MaxLength}
                             TotalLength: {TotalLength}
                             """);
    }
}

Example of error with placeholders 2 (exact value):

PropertyName: Input
PropertyValue: someinputtt
PropertyPath: Input
MinLength: 8
MaxLength: 8
TotalLength: 11

Validator MaximumLength.

To the list of validators

Description:

Ensures that the length of the string (type string) is not greater than the specified integer value (maximum number of characters).

Validator source code.

Code example:

// Сигнатура метода валидатора
public static IRuleBuilderOptions<T, string> MaximumLength<T>(
    this IRuleBuilder<T, string> ruleBuilder,
    int maximumLength
)
// Пример кода
using FluentValidation;
using FluentValidation.Results;

// Создаём модель и заполняем данными
Request request = new()
{
    Input = "someinput", // Длина 9 символов
};
// Создаём валидатор
RequestValidator validator = new();

// Валидируем модель, получаем результат
ValidationResult validationResult = validator.Validate(request);

// Валидация успешно пройдена?
if (validationResult.IsValid)
    Console.WriteLine("Валидация пройдена успешно!");
else
    // Выводим ошибки на консоль, разделяя символом |
    Console.WriteLine(validationResult.ToString("|"));

Console.ReadLine();

/// <summary>
/// Модель для валидатора <see cref="RequestValidator"/>
/// </summary>
internal record Request
{
    /// <summary>
    /// Валидируемое свойство
    /// </summary>
    public required string Input { get; init; }
}

/// <summary>
/// Валидатор для модели <see cref="Request"/>
/// </summary>
internal class RequestValidator : AbstractValidator<Request>
{
    public RequestValidator()
    {
        // Длина строки должна быть не более 9-ти символов
        RuleFor(request => request.Input).MaximumLength(9);
    }
}

Example of error:

'Input' должно быть длиной не более 9 символов. Количество введенных символов: 10.

Available placeholders:

{PropertyName} — name of the property being validated

{PropertyValue} — value of the property being validated

{PropertyPath} — full path to the property

{MaxLength} — maximum length

{TotalLength} — the length of the string value being checked

Example code with placeholders:

using FluentValidation;
using FluentValidation.Results;

// Создаём модель и заполняем данными
Request request = new()
{
    Input = "someinputе", // Длина 9 символов
};
// Создаём валидатор
RequestValidator validator = new();

// Валидируем модель, получаем результат
ValidationResult validationResult = validator.Validate(request);

// Валидация успешно пройдена?
if (validationResult.IsValid)
    Console.WriteLine("Валидация пройдена успешно!");
else
    // Выводим ошибки на консоль, разделяя символом |
    Console.WriteLine(validationResult.ToString("|"));

Console.ReadLine();

/// <summary>
/// Модель для валидатора <see cref="RequestValidator"/>
/// </summary>
internal record Request
{
    /// <summary>
    /// Валидируемое свойство
    /// </summary>
    public required string Input { get; init; }
}

/// <summary>
/// Валидатор для модели <see cref="Request"/>
/// </summary>
internal class RequestValidator : AbstractValidator<Request>
{
    public RequestValidator()
    {
        // Длина строки должна быть не более 9-ти символов
        RuleFor(request => request.Input)
            .MaximumLength(9)
            .WithMessage("""
                         PropertyName: {PropertyName}
                         PropertyValue: {PropertyValue}
                         PropertyPath: {PropertyPath}
                         MaxLength: {MaxLength}
                         TotalLength: {TotalLength}
                         """);
    }
}

Example of a placeholder error:

PropertyName: Input
PropertyValue: someinputе
PropertyPath: Input
MaxLength: 9
TotalLength: 10

MinimumLength validator.

To the list of validators

Description:

Ensures that the length of the string (type string) is not less than the specified integer value (minimum number of characters).

Validator source code.

Code example:

// Сигнатура метода валидатора
public static IRuleBuilderOptions<T, string> MinimumLength<T>(
    this IRuleBuilder<T, string> ruleBuilder,
    int minimumLength
)
// Пример кода
using FluentValidation;
using FluentValidation.Results;

// Создаём модель и заполняем данными
Request request = new()
{
    Input = "someinput", // Длина 9 символов
};
// Создаём валидатор
RequestValidator validator = new();

// Валидируем модель, получаем результат
ValidationResult validationResult = validator.Validate(request);

// Валидация успешно пройдена?
if (validationResult.IsValid)
    Console.WriteLine("Валидация пройдена успешно!");
else
    // Выводим ошибки на консоль, разделяя символом |
    Console.WriteLine(validationResult.ToString("|"));

Console.ReadLine();

/// <summary>
/// Модель для валидатора <see cref="RequestValidator"/>
/// </summary>
internal record Request
{
    /// <summary>
    /// Валидируемое свойство
    /// </summary>
    public required string Input { get; init; }
}

/// <summary>
/// Валидатор для модели <see cref="Request"/>
/// </summary>
internal class RequestValidator : AbstractValidator<Request>
{
    public RequestValidator()
    {
        // Длина строки должна быть не менее 9-ти символов
        RuleFor(request => request.Input).MinimumLength(9);
    }
}

Example of error:

'Input' должно быть длиной не менее 9 символов. Количество введенных символов: 8.

Available placeholders:

{PropertyName} — name of the property being validated

{PropertyValue} — value of the property being validated

{PropertyPath} — full path to the property

{MinLength} — minimum length

{TotalLength} — the length of the string value being checked

Example code with placeholders:

using FluentValidation;
using FluentValidation.Results;

// Создаём модель и заполняем данными
Request request = new()
{
    Input = "someinpu", // Длина 8 символов
};
// Создаём валидатор
RequestValidator validator = new();

// Валидируем модель, получаем результат
ValidationResult validationResult = validator.Validate(request);

// Валидация успешно пройдена?
if (validationResult.IsValid)
    Console.WriteLine("Валидация пройдена успешно!");
else
    // Выводим ошибки на консоль, разделяя символом |
    Console.WriteLine(validationResult.ToString("|"));

Console.ReadLine();

/// <summary>
/// Модель для валидатора <see cref="RequestValidator"/>
/// </summary>
internal record Request
{
    /// <summary>
    /// Валидируемое свойство
    /// </summary>
    public required string Input { get; init; }
}

/// <summary>
/// Валидатор для модели <see cref="Request"/>
/// </summary>
internal class RequestValidator : AbstractValidator<Request>
{
    public RequestValidator()
    {
        // Длина строки должна быть не менее 9-ти символов
        RuleFor(request => request.Input)
            .MinimumLength(9)
            .WithMessage("""
                         PropertyName: {PropertyName}
                         PropertyValue: {PropertyValue}
                         PropertyPath: {PropertyPath}
                         MinLength: {MinLength}
                         TotalLength: {TotalLength}
                         """);
    }
}

Example of a placeholder error:

PropertyName: Input
PropertyValue: someinpu
PropertyPath: Input
MinLength: 9
TotalLength: 8

LessThan validator.

To the list of validators

Description:

Ensures that the specified value, whose type implements the interface IComparablewill be less than the specified value, whose type also implements the interface IComparable.

Validator source code.

Code examples:

Let's check that the specified value is less than the specified value.

// Сигнатуры перегрузок методов валидатора в примере кода.
// Есть и другие, но их опущу, они связаны с nullable типами.
public static IRuleBuilderOptions<T, TProperty> LessThan<T, TProperty>(
    this IRuleBuilder<T, TProperty> ruleBuilder,
    TProperty valueToCompare
) where TProperty : IComparable<TProperty>, IComparable

public static IRuleBuilderOptions<T, TProperty?> LessThan<T, TProperty>(
    this IRuleBuilder<T, TProperty?> ruleBuilder,
	TProperty valueToCompare
) where TProperty : struct, IComparable<TProperty>, IComparable

using FluentValidation;
using FluentValidation.Results;

// Создаём модель и заполняем данными
Request request = new()
{
    InputInt = 4,
    InputNullableInt = 4,
    InputDateTime = DateTime.Now.AddDays(-5),
};
// Создаём валидатор
RequestValidator validator = new();

// Валидируем модель, получаем результат
ValidationResult validationResult = validator.Validate(request);

// Валидация успешно пройдена?
if (validationResult.IsValid)
    Console.WriteLine("Валидация пройдена успешно!");
else
    // Выводим ошибки на консоль, разделяя символом |
    Console.WriteLine(validationResult.ToString("|"));

Console.ReadLine();

/// <summary>
/// Модель для валидатора <see cref="RequestValidator"/>
/// </summary>
internal record Request
{
    /// <summary>
    /// Валидируемое свойство
    /// </summary>
    public required int InputInt { get; init; }
    /// <summary>
    /// Валидируемое свойство
    /// </summary>
    public required int? InputNullableInt { get; init; }
    /// <summary>
    /// Валидируемое свойство
    /// </summary>
    public required DateTime InputDateTime { get; init; }
}

/// <summary>
/// Валидатор для модели <see cref="Request"/>
/// </summary>
internal class RequestValidator : AbstractValidator<Request>
{
    public RequestValidator()
    {
        // Значение должно быть меньше чем 5
        RuleFor(request => request.InputInt).LessThan(5);
        // Значение должно быть меньше чем 5
        RuleFor(request => request.InputNullableInt).LessThan(5);
        // Значение должно быть меньше текущей даты/времени
        RuleFor(request => request.InputDateTime).LessThan(DateTime.Now);
    }
}

Let's check that the specified value is less than the specified property value.

// Сигнатура валидатора
public static IRuleBuilderOptions<T, TProperty?> LessThan<T, TProperty>(
    this IRuleBuilder<T, TProperty?> ruleBuilder,
    Expression<Func<T, TProperty>> expression
) where TProperty : struct, IComparable<TProperty>, IComparable
using FluentValidation;
using FluentValidation.Results;

// Создаём модель и заполняем данными
Request request = new()
{
    LessThanInt = 5, // Используется в валидаторе для сравнения "Меньше чем это число"
    Input = 4,
};
// Создаём валидатор
RequestValidator validator = new();

// Валидируем модель, получаем результат
ValidationResult validationResult = validator.Validate(request);

// Валидация успешно пройдена?
if (validationResult.IsValid)
    Console.WriteLine("Валидация пройдена успешно!");
else
    // Выводим ошибки на консоль, разделяя символом |
    Console.WriteLine(validationResult.ToString("|"));

Console.ReadLine();

/// <summary>
/// Модель для валидатора <see cref="RequestValidator"/>
/// </summary>
internal record Request
{
    /// <summary>
    /// Меньше чем это число
    /// </summary>
    public required int LessThanInt { get; init; }
    /// <summary>
    /// Валидируемое свойство
    /// </summary>
    public required int? Input { get; init; }
}

/// <summary>
/// Валидатор для модели <see cref="Request"/>
/// </summary>
internal class RequestValidator : AbstractValidator<Request>
{
    public RequestValidator()
    {
        // Значение должно быть меньше чем 5
        RuleFor(request => request.Input)
            .LessThan(request => request.LessThanInt);
    }
}

Example of error:

'Input' должно быть меньше '5'.

Available placeholders:

{PropertyName} — name of the property being validated

{PropertyValue} — value of the property being validated

{PropertyPath} — full path to the property

{ComparisonValue} — the value with which the comparison is performed

{ComparisonProperty} — the property with which the comparison is performed

Example code with placeholders 1 (using the property):

using FluentValidation;
using FluentValidation.Results;

// Создаём модель и заполняем данными
Request request = new()
{
    LessThanInt = 5, // Используется в валидаторе для сравнения "Меньше чем это число"
    Input = 5,
};
// Создаём валидатор
RequestValidator validator = new();

// Валидируем модель, получаем результат
ValidationResult validationResult = validator.Validate(request);

// Валидация успешно пройдена?
if (validationResult.IsValid)
    Console.WriteLine("Валидация пройдена успешно!");
else
    // Выводим ошибки на консоль, разделяя символом |
    Console.WriteLine(validationResult.ToString("|"));

Console.ReadLine();

/// <summary>
/// Модель для валидатора <see cref="RequestValidator"/>
/// </summary>
internal record Request
{
    /// <summary>
    /// Меньше чем это число
    /// </summary>
    public required int LessThanInt { get; init; }
    /// <summary>
    /// Валидируемое свойство
    /// </summary>
    public required int? Input { get; init; }
}

/// <summary>
/// Валидатор для модели <see cref="Request"/>
/// </summary>
internal class RequestValidator : AbstractValidator<Request>
{
    public RequestValidator()
    {
        // Значение должно быть меньше чем 5
        RuleFor(request => request.Input)
            .LessThan(request => request.LessThanInt)
            .WithMessage("""
                         PropertyName: {PropertyName}
                         PropertyValue: {PropertyValue}
                         PropertyPath: {PropertyPath}
                         ComparisonValue: {ComparisonValue}
                         ComparisonProperty: {ComparisonProperty}
                         """);
    }
}

Example of error with placeholders 1 (using property):

PropertyName: Input
PropertyValue: 5
PropertyPath: Input
ComparisonValue: 5
ComparisonProperty: Less Than Int

Example code with 2 placeholders (using integer literal):

using FluentValidation;
using FluentValidation.Results;

// Создаём модель и заполняем данными
Request request = new()
{
    Input = 5,
};
// Создаём валидатор
RequestValidator validator = new();

// Валидируем модель, получаем результат
ValidationResult validationResult = validator.Validate(request);

// Валидация успешно пройдена?
if (validationResult.IsValid)
    Console.WriteLine("Валидация пройдена успешно!");
else
    // Выводим ошибки на консоль, разделяя символом |
    Console.WriteLine(validationResult.ToString("|"));

Console.ReadLine();

/// <summary>
/// Модель для валидатора <see cref="RequestValidator"/>
/// </summary>
internal record Request
{
    /// <summary>
    /// Валидируемое свойство
    /// </summary>
    public required int? Input { get; init; }
}

/// <summary>
/// Валидатор для модели <see cref="Request"/>
/// </summary>
internal class RequestValidator : AbstractValidator<Request>
{
    public RequestValidator()
    {
        // Значение должно быть меньше чем 5
        RuleFor(request => request.Input)
            .LessThan(5)
            .WithMessage("""
                         PropertyName: {PropertyName}
                         PropertyValue: {PropertyValue}
                         PropertyPath: {PropertyPath}
                         ComparisonValue: {ComparisonValue}
                         ComparisonProperty: {ComparisonProperty}
                         """);
    }
}

Example of error with placeholders 2 (using integer literal):

PropertyName: Input
PropertyValue: 5
PropertyPath: Input
ComparisonValue: 5
ComparisonProperty: 

Validator LessThanOrEqualTo.

To the list of validators

Description:

Ensures that the specified value, whose type implements the interface IComparablewill be less than or equal to the specified value, whose type also implements the interface IComparable.

Validator source code.

Code examples:

Let's check that the specified value is less than or equal to the specified value.

// Сигнатуры перегрузок методов валидатора в примере кода.
// Есть и другие, но их опущу, они связаны с nullable типами.
public static IRuleBuilderOptions<T, TProperty> LessThanOrEqualTo<T, TProperty>(
    this IRuleBuilder<T, TProperty> ruleBuilder,
    TProperty valueToCompare
) where TProperty : IComparable<TProperty>, IComparable

public static IRuleBuilderOptions<T, TProperty?> LessThanOrEqualTo<T, TProperty>(
    this IRuleBuilder<T, TProperty?> ruleBuilder,
    TProperty valueToCompare
) where TProperty : struct, IComparable<TProperty>, IComparable
using FluentValidation;
using FluentValidation.Results;

// Создаём модель и заполняем данными
Request request = new()
{
    InputInt = 5,
    InputNullableInt = 5,
    InputDateTime = DateTime.Now,
};
// Создаём валидатор
RequestValidator validator = new();

// Валидируем модель, получаем результат
ValidationResult validationResult = validator.Validate(request);

// Валидация успешно пройдена?
if (validationResult.IsValid)
    Console.WriteLine("Валидация пройдена успешно!");
else
    // Выводим ошибки на консоль, разделяя символом |
    Console.WriteLine(validationResult.ToString("|"));

Console.ReadLine();

/// <summary>
/// Модель для валидатора <see cref="RequestValidator"/>
/// </summary>
internal record Request
{
    /// <summary>
    /// Валидируемое свойство
    /// </summary>
    public required int InputInt { get; init; }
    /// <summary>
    /// Валидируемое свойство
    /// </summary>
    public required int? InputNullableInt { get; init; }
    /// <summary>
    /// Валидируемое свойство
    /// </summary>
    public required DateTime InputDateTime { get; init; }
}

/// <summary>
/// Валидатор для модели <see cref="Request"/>
/// </summary>
internal class RequestValidator : AbstractValidator<Request>
{
    public RequestValidator()
    {
        // Значение должно быть меньше или равно 5-ти
        RuleFor(request => request.InputInt).LessThanOrEqualTo(5);
        // Значение должно быть меньше или равно 5-ти
        RuleFor(request => request.InputNullableInt).LessThanOrEqualTo(5);
        // Значение должно быть меньше или равно текущей дате/времени
        RuleFor(request => request.InputDateTime).LessThanOrEqualTo(DateTime.Now);
    }
}

Check that the specified value is less than or equal to the specified property value.

// Сигнатура валидатора
public static IRuleBuilderOptions<T, TProperty?> LessThanOrEqualTo<T, TProperty>(
    this IRuleBuilder<T, TProperty?> ruleBuilder,
    Expression<Func<T, TProperty>> expression
) where TProperty : struct, IComparable<TProperty>, IComparable
using FluentValidation;
using FluentValidation.Results;

// Создаём модель и заполняем данными
Request request = new()
{
    LessThanInt = 5, // Используется в валидаторе для сравнения "Меньше или равно этому числу"
    Input = 5,
};
// Создаём валидатор
RequestValidator validator = new();

// Валидируем модель, получаем результат
ValidationResult validationResult = validator.Validate(request);

// Валидация успешно пройдена?
if (validationResult.IsValid)
    Console.WriteLine("Валидация пройдена успешно!");
else
    // Выводим ошибки на консоль, разделяя символом |
    Console.WriteLine(validationResult.ToString("|"));

Console.ReadLine();

/// <summary>
/// Модель для валидатора <see cref="RequestValidator"/>
/// </summary>
internal record Request
{
    /// <summary>
    /// Меньше или равно этому числу
    /// </summary>
    public required int LessThanInt { get; init; }
    /// <summary>
    /// Валидируемое свойство
    /// </summary>
    public required int? Input { get; init; }
}

/// <summary>
/// Валидатор для модели <see cref="Request"/>
/// </summary>
internal class RequestValidator : AbstractValidator<Request>
{
    public RequestValidator()
    {
        // Значение должно быть меньше или равно 5-ти
        RuleFor(request => request.Input)
            .LessThanOrEqualTo(request => request.LessThanInt);
    }
}

Example of error:

'Input' должно быть меньше или равно '5'.

Available placeholders:

{PropertyName} — name of the property being validated

{PropertyValue} — value of the property being validated

{PropertyPath} — full path to the property

{ComparisonValue} — the value with which the comparison is performed

{ComparisonProperty} — the property with which the comparison is performed

Example code with placeholders 1 (using property):

using FluentValidation;
using FluentValidation.Results;

// Создаём модель и заполняем данными
Request request = new()
{
    LessThanInt = 5, // Используется в валидаторе для сравнения "Меньше или равно этому числу"
    Input = 6,
};
// Создаём валидатор
RequestValidator validator = new();

// Валидируем модель, получаем результат
ValidationResult validationResult = validator.Validate(request);

// Валидация успешно пройдена?
if (validationResult.IsValid)
    Console.WriteLine("Валидация пройдена успешно!");
else
    // Выводим ошибки на консоль, разделяя символом |
    Console.WriteLine(validationResult.ToString("|"));

Console.ReadLine();

/// <summary>
/// Модель для валидатора <see cref="RequestValidator"/>
/// </summary>
internal record Request
{
    /// <summary>
    /// Меньше или равно этому числу
    /// </summary>
    public required int LessThanInt { get; init; }
    /// <summary>
    /// Валидируемое свойство
    /// </summary>
    public required int? Input { get; init; }
}

/// <summary>
/// Валидатор для модели <see cref="Request"/>
/// </summary>
internal class RequestValidator : AbstractValidator<Request>
{
    public RequestValidator()
    {
        // Значение должно быть меньше или равно 5-ти
        RuleFor(request => request.Input)
            .LessThanOrEqualTo(request => request.LessThanInt)
            .WithMessage("""
                         PropertyName: {PropertyName}
                         PropertyValue: {PropertyValue}
                         PropertyPath: {PropertyPath}
                         ComparisonValue: {ComparisonValue}
                         ComparisonProperty: {ComparisonProperty}
                         """);
    }
}

Example of error with placeholders 1 (using property):

PropertyName: Input
PropertyValue: 6
PropertyPath: Input
ComparisonValue: 5
ComparisonProperty: Less Than Int

Example code with 2 placeholders (using integer literal):

using FluentValidation;
using FluentValidation.Results;

// Создаём модель и заполняем данными
Request request = new()
{
    Input = 6,
};
// Создаём валидатор
RequestValidator validator = new();

// Валидируем модель, получаем результат
ValidationResult validationResult = validator.Validate(request);

// Валидация успешно пройдена?
if (validationResult.IsValid)
    Console.WriteLine("Валидация пройдена успешно!");
else
    // Выводим ошибки на консоль, разделяя символом |
    Console.WriteLine(validationResult.ToString("|"));

Console.ReadLine();

/// <summary>
/// Модель для валидатора <see cref="RequestValidator"/>
/// </summary>
internal record Request
{
    /// <summary>
    /// Валидируемое свойство
    /// </summary>
    public required int? Input { get; init; }
}

/// <summary>
/// Валидатор для модели <see cref="Request"/>
/// </summary>
internal class RequestValidator : AbstractValidator<Request>
{
    public RequestValidator()
    {
        // Значение должно быть меньше или равно 5-ти
        RuleFor(request => request.Input)
            .LessThanOrEqualTo(5)
            .WithMessage("""
                         PropertyName: {PropertyName}
                         PropertyValue: {PropertyValue}
                         PropertyPath: {PropertyPath}
                         ComparisonValue: {ComparisonValue}
                         ComparisonProperty: {ComparisonProperty}
                         """);
    }
}

Example of error with placeholders 2 (using integer literal):

PropertyName: Input
PropertyValue: 6
PropertyPath: Input
ComparisonValue: 5
ComparisonProperty: 

← Previous part

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *