DEV Community

Alexander Nitrovich
Alexander Nitrovich

Posted on Originally published at blog.eurovalidate.com

Validate IBAN in C#

Ensuring that International Bank Account Numbers (IBANs) are valid is crucial for any fintech or banking application built with C#. This article provides an in-depth, developer-friendly guide to implementing IBAN validation in C#. We'll break down the process into understandable steps, including regular expression (regex) checks and the mod97 algorithm. By the end, you'll be equipped to seamlessly integrate this functionality, ensuring compliance and accuracy in your financial systems.

Introduction

The International Bank Account Number (IBAN) is a standardized method for identifying bank accounts across the globe. Validating IBANs is vital for fintech and banking applications to prevent transaction errors and ensure financial integrity. In this guide, we will explore how C# developers can implement IBAN validation, which is a foundational aspect of building reliable payment systems.

Understanding IBAN Format and Validation Requirements

An IBAN consists of a country code, check digits, and a Basic Bank Account Number (BBAN). Validating an IBAN involves two primary checks:

  • Syntax Check: Verifying the correct format using regular expressions.
  • Algorithmic Check: Applying the mod97 algorithm to ensure numerical validity.

Setting Up Your C# Environment

Before you start coding, ensure your development environment is ready:

  • .NET Version: Use .NET Core or .NET Framework as required by your project.
  • IDE: Visual Studio or any C# compatible text editor.
  • Libraries: Built-in C# libraries suffice for this task.

Implementing IBAN Validation in C

Step 1: Validating the IBAN Format using Regular Expressions

Use the following regex pattern to ensure the basic syntax of an IBAN:

string ibanPattern = @"^[A-Z]{2}\d{2}[A-Z0-9]{1,30}$";
if (!Regex.IsMatch(iban, ibanPattern))
{
    Console.WriteLine("Invalid IBAN format.");
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Converting Letters to Numbers and Performing the mod97 Algorithm

Here's how you can implement the mod97 algorithm in C#:

public bool ValidateIban(string iban)
{
    if (string.IsNullOrEmpty(iban)) return false;

    // Remove spaces and convert to uppercase
    iban = iban.Replace(" ", "").ToUpper();

    // Use regex for basic format check
    string pattern = @"^[A-Z]{2}\d{2}[A-Z0-9]+$";
    if (!Regex.IsMatch(iban, pattern)) return false;

    // Move the first four characters to the end of the string
    string rearrangedIban = iban.Substring(4) + iban.Substring(0, 4);

    // Convert letters to numbers: A = 10, B = 11, ... Z = 35
    StringBuilder numericIban = new StringBuilder();
    foreach (char ch in rearrangedIban)
    {
        if (char.IsLetter(ch))
        {
            int value = ch - 'A' + 10;
            numericIban.Append(value);
        }
        else
        {
            numericIban.Append(ch);
        }
    }

    // Perform mod97 calculation
    string remainder = numericIban.ToString();
    int mod = 0;
    while (remainder.Length > 0)
    {
        int chunkLength = Math.Min(9, remainder.Length);
        string part = mod.ToString() + remainder.Substring(0, chunkLength);
        mod = int.Parse(part) % 97;
        remainder = remainder.Substring(chunkLength);
    }
    return mod == 1;
}
Enter fullscreen mode Exit fullscreen mode

Code Example: Complete IBAN Validation Function

Here's a full, production-ready function that combines the regex check and mod97 validation in C#:

public bool ValidateIban(string iban)
{
    if (string.IsNullOrEmpty(iban)) return false;

    iban = iban.Replace(" ", "").ToUpper();
    string pattern = @"^[A-Z]{2}\d{2}[A-Z0-9]+$";
    if (!Regex.IsMatch(iban, pattern)) return false;

    string rearrangedIban = iban.Substring(4) + iban.Substring(0, 4);
    StringBuilder numericIban = new StringBuilder();
    foreach (char ch in rearrangedIban)
    {
        if (char.IsLetter(ch)) numericIban.Append(ch - 'A' + 10);
        else numericIban.Append(ch);
    }

    string remainder = numericIban.ToString();
    int mod = 0;
    while (remainder.Length > 0)
    {
        int chunkLength = Math.Min(9, remainder.Length);
        string part = mod.ToString() + remainder.Substring(0, chunkLength);
        mod = int.Parse(part) % 97;
        remainder = remainder.Substring(chunkLength);
    }
    return mod == 1;
}
Enter fullscreen mode Exit fullscreen mode

Testing and Error Handling

Testing your validation function involves using both valid and invalid IBANs:

  • Valid: DE89370400440532013000
  • Invalid: FR40303265045

Common pitfalls include not handling null or empty IBAN strings and incorrect format patterns. Ensure to catch exceptions and log errors for troubleshooting.

Best Practices and Optimization Tips

  • Integration: Embed the validation logic within middleware or service layers for comprehensive error handling.
  • Performance: Optimize regex checks and batch process IBANs when dealing with large datasets to avoid latency issues.

Conclusion

Implementing your own IBAN validation in C# enhances the reliability of your financial applications, ensuring each transaction is routed correctly. Explore our API Documentation for more robust solutions. Get your free API key at EuroValidate to further secure your fintech systems.

By following this guide, C# developers can accurately validate IBANs, paving the way for secure and compliant payment processing applications.

Top comments (0)