Skip to content

IbanNet.FluentValidation

Martijn Bodeman edited this page Aug 10, 2023 · 10 revisions

The IbanNet.FluentValidation package provides FluentValidation support to validate IBAN user input.

Example model

Assuming we have a string property for the IBAN.

public class InputModel
{
    public string BackAccountNumber { get; set; }
}

Create a new validator

using FluentValidation;
using IbanNet;
using IbanNet.FluentValidation;

public class InputModelValidator : AbstractValidator<InputModel>
{
    public InputModelValidator(IIbanValidator ibanValidator)
    {
        RuleFor(x => x.BankAccountNumber).NotNull().Iban(ibanValidator);
    }
}

Strict

By default, IBAN's submitted to the validator will be validated strictly according to the ISO 13616 specification (if using the SWIFT registry provider). If you wish to allow more relaxed validation that ignores casing rules and whitespace in the user input, set the strict boolean parameter to false. It is however recommended that if you do so, to use the IbanParser to parse the value further down in your application code to ensure it is fully conformant to the ISO 13616 specification.

RuleFor(x => x.BankAccountNumber).NotNull().Iban(ibanValidator, strict: false);

Register the validator

Make sure to register:

  • IbanNet
  • the validator
  • FluentValidation

.NET Core example

services.AddIbanNet();
services.AddTransient<IValidator<InputModel>, InputModelValidator>()
services.AddFluentValidation();

Not required

The .Iban() validator extension method does not require a property to be set, and as such a null value will be validated successfully. An empty string property however IS considered invalid. To disallow null values chain with the built-in FluentValidation .NotNull() extension.