Geeks With Blogs
Bob Goedkoop Programming C# on Microsoft's .NET plaform

Technorati Tags: ,,,,
For my current project we need to validate IBAN numbers. IBAN numbers are validated with an ISO 7064 mod-97-10 calculation where the remainder must equal 1

 
static public bool Validate(string iban)
        {
            // pre-conditions
            if ( string.IsNullOrEmpty( iban ) || (!Regex.IsMatch(iban, "^[A-Z0-9]") ) )
            {
                return false;
            }
 
            // clean-up IBAN
            iban = iban.Replace(" ", String.Empty);
 
            // 1.Move the four initial characters to the end of the string
            string iban2 = iban.Substring(4, iban.Length - 4) + iban.Substring(0, 4);
 
            // 2.Replace the letters in the string with digits, expanding the string as necessary, such that A=10, B=11 and Z=35.
            const int asciiShift = 55;
            var sb = new StringBuilder();
            foreach (char c in iban2)
            {
                int x;
                if (Char.IsLetter(c)) {
                    x = c - asciiShift;
                }
                else {
                    x = int.Parse(c.ToString(), CultureInfo.InvariantCulture);
                }
                sb.Append(x);
            }
 
            // 3.Convert the string to an integer and mod-97 the entire number
            string checkSumString = sb.ToString();
            int checksum = int.Parse( checkSumString.Substring(0, 1), CultureInfo.InvariantCulture );
            for (var i = 1; i < checkSumString.Length; i++)
            {
                int v = int.Parse(checkSumString.Substring(i, 1), CultureInfo.InvariantCulture);
                checksum *= 10;
                checksum += v;
                checksum %= 97;
            }
            return ( checksum == 1 );
        }
   

Since I didn’t expect we would be the first to want to implement this in C# we first did a quick search on the web for an existing implementation. The following resources have been used to come to the above implementation:

Posted on Thursday, July 4, 2013 1:25 PM C# , IBAN | Back to top


Comments on this post: Mod 97

# re: Mod 97
Requesting Gravatar...
!Regex.IsMatch(iban, "^[A-Z0-9]" should be !Regex.IsMatch(iban, "^[\\w\\d\\b]+$" to check not only the first char but also the rest of the line, otherwise this string "A#" would be true.

thanks for the code!
Left by none on Jul 01, 2014 11:22 AM

Your comment:
 (will show your gravatar)


Copyright © Bob Goedkoop | Powered by: GeeksWithBlogs.net