Overview of the FluentValidation library. Part 7.1. Built-in validators

This part covers the following validators:

  • NotNull (value is not equal null)

  • Null (value equals null)

  • NotEmpty (value is not equal nullempty line, spaces, 0 collection elements)

  • Empty (value equals nullempty line, spaces, 0 collection elements)

  • NotEqual (the value is not equal to the defined one or is not equal to the specified property)

  • Equal (value is equal to a defined or equal to a specified property)

List of all built-in validators:

  • NotNull

  • Null

  • NotEmpty

  • Empty

  • NotEqual

  • Equal

  • Length

  • MaximumLength

  • MinimumLength

  • LessThan

  • LessThanOrEqual

  • GreaterThan

  • GreaterThanOrEqual

  • Must

  • Matches

  • EmailAddress

  • CreditCard

  • IsInEnum

  • IsEnumName

  • ExclusiveBetween

  • InclusiveBetween

  • PrecisionScale

NotNull validator.

Description:

Ensures that the specified property is not equal to the value null.

Sample code:

// Модель адреса
public class Address
{
  // Фактический адрес
  public string? Actual { get; set; }
}

// Модель клиента
public class Customer
{
  // Адрес
  public Address? Address { get; set; }
}

// Валидатор для модели клиента
public class CustomerValidator : AbstractValidator<Customer>
{
  public CustomerValidator()
  {
    // Свойство Actual должно быть не равно null
    RuleFor(customer => customer.Address.Actual)
      .NotNull();
  }
}

// Здесь выполняем валидацию как обычно
static void Main(string[] args)
{
  ValidatorOptions.Global.LanguageManager.Culture = new CultureInfo("ru-RU");

  // Здесь задаём данные
  var customer = new Customer
  {
    Address = new()
    {
      Actual = null
    }
  };
  
  var validator = new CustomerValidator();
  var result = validator.Validate(customer);

  Console.WriteLine(result.ToString(Environment.NewLine));
}

Error example:

'Address Actual' должно быть заполнено.

Available fillers:

{PropertyName} — name of the property being validated

{PropertyValue} — value of the property being validated

{PropertyPath} – full path to the property

Example code with placeholders:

RuleFor(customer => customer.Address.Actual)
  .NotNull()
    .WithMessage("PropertyName: {PropertyName}\n" +
    "PropertyValue: {PropertyValue}\n" +
    "PropertyPath: {PropertyPath}");

Example of an error with placeholders:

PropertyName: Address Actual
PropertyValue:
PropertyPath: Address.Actual

Null validator.

Ensures that the specified property is equal to the value null.

Sample code:

// Модель адреса
public class Address
{
  // Фактический адрес
  public string? Actual { get; set; }
}

// Модель клиента
public class Customer
{
  // Адрес
  public Address? Address { get; set; }
}

// Валидатор для модели клиента
public class CustomerValidator : AbstractValidator<Customer>
{
  public CustomerValidator()
  {
    // Свойство Actual должно быть равно null
    RuleFor(customer => customer.Address.Actual)
      .Null();
  }
}

// Здесь выполняем валидацию как обычно
static void Main(string[] args)
{
  ValidatorOptions.Global.LanguageManager.Culture = new CultureInfo("ru-RU");

  // Здесь задаём данные
  var customer = new Customer
  {
    Address = new()
    {
      Actual = "SomeAddress"
    }
  };

  var validator = new CustomerValidator();
  var result = validator.Validate(customer);

  Console.WriteLine(result.ToString(Environment.NewLine));
}

Error example:

'Address Actual' должно быть пустым.

Available fillers:

{PropertyName} — name of the property being validated

{PropertyValue} — value of the property being validated

{PropertyPath} – full path to the property

Example code with placeholders:

RuleFor(customer => customer.Address.Actual)
  .Null()
    .WithMessage("PropertyName: {PropertyName}\n" +
    "PropertyValue: {PropertyValue}\n" +
    "PropertyPath: {PropertyPath}");

Example of an error with placeholders:

PropertyName: Address Actual
PropertyValue: SomeAddress
PropertyPath: Address.Actual

Validator NotEmpty.

Ensures that the specified property is not equal to the value nullempty string, spaces or default values ​​for value types, for example, 0 for type int. If used on type IEnumerableor its derivatives (such as arrays, collections, etc.), the validator ensures that the data array contains at least one element.

Sample code:

// Модель адреса
public class Address
{
  // Фактический адрес
  public string? Actual { get; set; }
}

// Модель клиента
public class Customer
{
  // Адрес
  public Address? Address { get; set; }
}

// Валидатор для модели клиента
public class CustomerValidator : AbstractValidator<Customer>
{
  public CustomerValidator()
  {
    // Свойство Actual должно быть не равно null, пустой строке, пробелам
    RuleFor(customer => customer.Address.Actual)
      .NotEmpty();
  }
}

// Здесь выполняем валидацию как обычно
static void Main(string[] args)
{
  ValidatorOptions.Global.LanguageManager.Culture = new CultureInfo("ru-RU");

  // Здесь задаём данные
  var customer = new Customer
  {
    Address = new()
    {
      Actual = ""
    }
  };

  var validator = new CustomerValidator();
  var result = validator.Validate(customer);

  Console.WriteLine(result.ToString(Environment.NewLine));
}

Error example:

'Address Actual' должно быть заполнено.

Available fillers:

{PropertyName} — name of the property being validated

{PropertyValue} — value of the property being validated

{PropertyPath} – full path to the property

Example code with placeholders:

RuleFor(customer => customer.Address.Actual)
  .NotEmpty()
    .WithMessage("PropertyName: {PropertyName}\n" +
    "PropertyValue: {PropertyValue}\n" +
    "PropertyPath: {PropertyPath}");

Example of an error with placeholders:

PropertyName: Address Actual
PropertyValue:
PropertyPath: Address.Actual

Validator Empty.

Ensures that the specified property is equal to the value nullempty string, spaces or default values ​​for value types, for example, 0 for type int. If used on type IEnumerableor its derivatives (such as arrays, collections, etc.), the validator ensures that the data array contains no elements.

Sample code:

// Модель адреса
public class Address
{
  // Фактический адрес
  public string? Actual { get; set; }
}

// Модель клиента
public class Customer
{
  // Адрес
  public Address? Address { get; set; }
}

// Валидатор для модели клиента
public class CustomerValidator : AbstractValidator<Customer>
{
  public CustomerValidator()
  {
    // Свойство Actual должно быть равно null, пустой строке, пробелам
    RuleFor(customer => customer.Address.Actual)
      .Empty();
  }
}

// Здесь выполняем валидацию как обычно
static void Main(string[] args)
{
  ValidatorOptions.Global.LanguageManager.Culture = new CultureInfo("ru-RU");

  // Здесь задаём данные
  var customer = new Customer
  {
    Address = new()
    {
      Actual = "value"
    }
  };

  var validator = new CustomerValidator();
  var result = validator.Validate(customer);

  Console.WriteLine(result.ToString(Environment.NewLine));
}

Error example:

'Address Actual' должно быть пустым.

Available fillers:

{PropertyName} — name of the property being validated

{PropertyValue} — value of the property being validated

{PropertyPath} – full path to the property

Example code with placeholders:

RuleFor(customer => customer.Address.Actual)
  .Empty()
    .WithMessage("PropertyName: {PropertyName}\n" +
    "PropertyValue: {PropertyValue}\n" +
    "PropertyPath: {PropertyPath}");

Example of an error with placeholders:

PropertyName: Address Actual
PropertyValue: value
PropertyPath: Address.Actual

Validator NotEqual.

Ensures that a specified property is not equal to a specified value (or is not equal to the value of another specified property).

First code example (not equal to a specific value):

// Модель клиента
public class Customer
{
  // Номер телефона клиента
  public string? PhoneNumber { get; set; }
}

// Валидатор для модели клиента
public class CustomerValidator : AbstractValidator<Customer>
{
  public CustomerValidator()
  {
    // Свойство PhoneNumber должно быть не равно значению "89998887766"
    RuleFor(customer => customer.PhoneNumber)
      .NotEqual("89998887766");
  }
}

// Здесь выполняем валидацию как обычно
static void Main(string[] args)
{
  ValidatorOptions.Global.LanguageManager.Culture = new CultureInfo("ru-RU");
  
  // Здесь задаём данные
  var customer = new Customer
  {
    PhoneNumber = "89998887766"
  };
  
  var validator = new CustomerValidator();
  var result = validator.Validate(customer);
  
  Console.WriteLine(result.ToString(Environment.NewLine));
}

Error example:

'Phone Number' не должно быть равно '89998887766'.

Second code example (not equal to the value of another specified property):

// Модель клиента
public class Customer
{
  // Номер телефона клиента
  public string? PhoneNumber { get; set; }
  // Номер телефона третьего лица
  public string? ThirdPartyPhoneNumber { get; set; }
}
// Валидатор для модели клиента
public class CustomerValidator : AbstractValidator<Customer>
{
  public CustomerValidator()
  {
    // Свойство PhoneNumber должно быть не равно значению
    // свойства ThirdPartyPhoneNumber
    RuleFor(customer => customer.PhoneNumber)
      .NotEqual(customer => customer.ThirdPartyPhoneNumber);
  }
}
// Здесь выполняем валидацию как обычно
static void Main(string[] args)
{
  ValidatorOptions.Global.LanguageManager.Culture = new CultureInfo("ru-RU");
  
  // Здесь задаём данные
  var customer = new Customer
  {
    PhoneNumber = "89998887766",
    ThirdPartyPhoneNumber = "89998887766"
  };
  
  var validator = new CustomerValidator();
  var result = validator.Validate(customer);
  
  Console.WriteLine(result.ToString(Environment.NewLine));
}

Error example:

'Phone Number' не должно быть равно '89998887766'.

Available fillers:

{PropertyName} — name of the property being validated

{PropertyValue} — value of the property being validated

{PropertyPath} – full path to the property

{ComparisonProperty} — the name of the property with which the comparison is made

{ComparisonValue} – the value with which the comparison is made

First code example with placeholders (not equal to a specific value):

RuleFor(customer => customer.PhoneNumber)
  .NotEqual("89998887766")
    .WithMessage("PropertyName: {PropertyName}\n" +
    "PropertyValue: {PropertyValue}\n" +
    "PropertyPath: {PropertyPath}\n" +
    "ComparisonProperty: {ComparisonProperty}\n" +
    "ComparisonValue: {ComparisonValue}");

First example of an error with placeholders:

PropertyName: Phone Number
PropertyValue: 89998887766
PropertyPath: PhoneNumber
ComparisonProperty:
ComparisonValue: 89998887766

Second code example with placeholders (not equal to the value of another specified property):

RuleFor(customer => customer.PhoneNumber)
  .NotEqual(customer => customer.ThirdPartyPhoneNumber)
    .WithMessage("PropertyName: {PropertyName}\n" +
    "PropertyValue: {PropertyValue}\n" +
    "PropertyPath: {PropertyPath}\n" +
    "ComparisonProperty: {ComparisonProperty}\n" +
    "ComparisonValue: ");

Second example of an error with placeholders:

PropertyName: Phone Number
PropertyValue: 89998887766
PropertyPath: PhoneNumber
ComparisonProperty: Third Party Phone Number
ComparisonValue: 89998887766

Equal validator.

Description:

Ensures that a specified property is equal to a specified value (or equal to the value of another specified property).

First code example (equal to a specific value):

// Модель адреса
public class Address
{
  // Фактический адрес
  public string? Actual { get; set; }
}

// Модель клиента
public class Customer
{
  // Адрес
  public Address? Address { get; set; }
}

// Валидатор для модели клиента
public class CustomerValidator : AbstractValidator<Customer>
{
  public CustomerValidator()
  {
    // Свойство Actual должно быть равно значению SomeAddress
    RuleFor(customer => customer.Address.Actual)
      .Equal("SomeAddress");
  }
}

// Здесь выполняем валидацию как обычно
static void Main(string[] args)
{
  ValidatorOptions.Global.LanguageManager.Culture = new CultureInfo("ru-RU");

  // Здесь задаём данные
  var customer = new Customer
  {
    Address = new()
    {
      Actual = "NotSomeAddress"
    }
  };

  var validator = new CustomerValidator();
  var result = validator.Validate(customer);

  Console.WriteLine(result.ToString(Environment.NewLine));
}

Error example:

'Address Actual' должно быть равно 'SomeAddress'.

Second code example (equal to the value of another specified property):

// Модель клиента
public class Customer
{
  // Пароль
  public string? Password { get; set; }
  // Подтверждение пароля
  public string? PasswordConfirmation { get; set; }
}

// Валидатор для модели клиента
public class CustomerValidator : AbstractValidator<Customer>
{
  public CustomerValidator()
  {
    // Значение свойства Password должно быть равно значению свойства
    // PasswordConfirmation
    RuleFor(customer => customer.Password)
      .Equal(customer => customer.PasswordConfirmation);
  }
}

// Здесь выполняем валидацию как обычно
static void Main(string[] args)
{
  ValidatorOptions.Global.LanguageManager.Culture = new CultureInfo("ru-RU");

  // Здесь задаём данные
  var customer = new Customer
  {
    Password = "qwerty1",
    PasswordConfirmation = "qwerty2"
  };

  var validator = new CustomerValidator();
  var result = validator.Validate(customer);

  Console.WriteLine(result.ToString(Environment.NewLine));
}

Error example:

'Password' должно быть равно 'qwerty2'.

Available fillers:

{PropertyName} — name of the property being validated

{PropertyValue} — value of the property being validated

{PropertyPath} – full path to the property

{ComparisonProperty} — the name of the property with which the comparison is made

{ComparisonValue} – the value with which the comparison is made

First code example with placeholders (equal to a specific value):

RuleFor(customer => customer.Address.Actual)
  .Equal("SomeAddress")
    .WithMessage("PropertyName: {PropertyName}\n" +
    "PropertyValue: {PropertyValue}\n" +
    "PropertyPath: {PropertyPath}\n" +
    "ComparisonProperty: {ComparisonProperty}\n" +
    "ComparisonValue: {ComparisonValue}");

First example of an error with placeholders:

PropertyName: Address Actual
PropertyValue: NotSomeAddress
PropertyPath: Address.Actual
ComparisonProperty:
ComparisonValue: SomeAddress

Second code example with placeholders (equal to the value of another specified property):

RuleFor(customer => customer.Password)
  .Equal(customer => customer.PasswordConfirmation)
    .WithMessage("PropertyName: {PropertyName}\n" +
    "PropertyValue: {PropertyValue}\n" +
    "PropertyPath: {PropertyPath}\n" +
    "ComparisonProperty: {ComparisonProperty}\n" +
    "ComparisonValue: {ComparisonValue}");

Second example of an error with placeholders:

PropertyName: Password
PropertyValue: qwerty1
PropertyPath: Password
ComparisonProperty: Password Confirmation
ComparisonValue: qwerty2

You can specify the type of comparison through the second argument, using an enumeration StringComparer. The default value is StringComparer.Ordinal (case-sensitive ordinal comparison):

// Cоответствует определённому значению (порядковое сравнение без учёта регистра)
RuleFor(customer => customer.Address.Actual)
  .Equal("SomeAddress", StringComparer.OrdinalIgnoreCase);

// Соответствует значению другого указанного свойства (порядковое сравнение без учёта регистра)
RuleFor(customer => customer.Password)
  .Equal(customer => customer.PasswordConfirmation, StringComparer.OrdinalIgnoreCase)

← Previous part

Similar Posts

Leave a Reply

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