Skip to content
Martijn Bodeman edited this page Oct 9, 2022 · 14 revisions

Use the IbanValidator for full control over the validation.

The benefit of using the validator is that it implements the IIbanValidator interface and can thus be easily mocked. Additionally, the ValidationResult provides extra context, like the matched country (if any).

Example

IIbanValidator validator = new IbanValidator();
ValidationResult validationResult = validator.Validate("NL91ABNA041716430");
if (validationResult.IsValid)
{
    // For example:
    if (validationResult.Country.TwoLetterISORegionName != "NL")
    {
        throw new InvalidOperationException("Please provide a Dutch bank account.");
    }
}
else
{
    Console.WriteLine(validationResult.Error.ErrorMessage);
}

Considerations

  • When using the validator directly, it validates the input to exactly match the defined country specific pattern.
  • The validator does NOT ignore spaces, unless explicitly defined in the country specific pattern.
  • The validator MAY be case sensitive, if so defined in the country specific pattern.
  • The validator rejects null (unlike the FluentValidation/DataAnnotation integration packages, which intentionally allow null).

⚠️ The integration packages for DataAnnotations and FluentValidation behave slighly differently. When using those, do not just assume that if the IBAN validates that the value is correctly formatted. Use the IbanParser after successful validation instead, to guarantee correct persistence/serialization of IBAN's to downstream systems (like databases, other API's), using the Iban.ToString() formatting API.

Error results

When an IBAN is invalid, the error is reported in the ValidationResult.Error property. Below a list of possible built-in errors:

Type Description
ErrorResult The base type of all errors. Custom rules should derive from this type to provide their own specific error.
IllegalCharactersResult Contains non alphanumeric characters.
IllegalCountryCodeCharactersResult Contains invalid country code characters.
InvalidCheckDigitsResult Check digits are invalid.
InvalidLengthResult Length is invalid.
InvalidStructureResult Does not match expected pattern.
UnknownCountryCodeResult The country code is unknown (not registered with IbanNet).

Example

ValidationResult validationResult = validator.Validate(..);
if (validationResult.Error is InvalidLengthResult)
{
    .. 
}