Skip to content
skwasjer edited this page Feb 19, 2021 · 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

  • The validator ignores whitespace.
  • The validator rejects null (unlike the FluentValidation/DataAnnotation integration packages, which intentionally allow null).
  • The validator 'may' be case sensitive. It will largely depend on the rules defined for each individual country.
  • Do not just assume that if the IBAN validates that the value is correctly formatted. Use the IbanParser instead to guarantee correct persistence/serialization of IBAN's to downstream systems (like databases, other API's).

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)
{
    .. 
}