Skip to content
skwas edited this page Dec 11, 2019 · 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);
}

Error results

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

  • IllegalCharactersResult
  • IllegalCountryCodeCharactersResult
  • InvalidCheckDigitsResult
  • InvalidLengthResult
  • InvalidStructureResult
  • UnknownCountryCodeResult

Example

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

Strict vs loose validation

IbanNet by default validates every IBAN using strict validation rules. You can choose to use loose validation mode, which is a little less strict (the structure of an IBAN is not validated, allowing false positives) but also around 20% faster.

To enable loose mode, configure the validator:

var validator = new IbanValidator(new IbanValidatorOptions
{
    ValidationMethod = new LooseValidation()
});

There are some legitimate use cases where loose validation is acceptable, for instance within internal service domain boundaries, where the assumption can be safely made that an IBAN has already been strictly validated in prior workflows/processes.