ExtensionMethod.NET Home of 820 C#, Visual Basic, F# and Javascript extension methods

IsIsin

Determines if a string is a valid ISIN (International Securities Identification Number) code.

Source

/// <summary>
/// Determines if a string is a valid ISIN (International Securities Identification Number) code
/// </summary>
/// <remarks>
    /// Port from Java code at http://en.wikipedia.org/wiki/International_Securities_Identification_Number
    /// </remarks>
public static class IsinHelper
{
    private static readonly Regex Pattern = new Regex("[A-Z]{2}([A-Z0-9]){10}", RegexOptions.Compiled);

    /// <summary>
    /// True se a string passada for um ISIN válido
    /// </summary>
    public static bool IsIsin(this string isin)
    {
        if (string.IsNullOrEmpty(isin))
        {
            return false;
        }
        if (!Pattern.IsMatch(isin))
        {
            return false;
        }

        var digits = new int[22];
        int index = 0;
        for (int i = 0; i < 11; i++)
        {
            char c = isin[i];
            if (c >= '0' && c <= '9')
            {
                digits[index++] = c - '0';
            }
            else if (c >= 'A' && c <= 'Z')
            {
                int n = c - 'A' + 10;
                int tens = n/10;
                if (tens != 0)
                {
                    digits[index++] = tens;
                }
                digits[index++] = n%10;
            }
            else
            {
                // Not a digit or upper-case letter.
                return false;
            }
        }
        int sum = 0;
        for (int i = 0; i < index; i++)
        {
            int digit = digits[index - 1 - i];
            if (i%2 == 0)
            {
                digit *= 2;
            }
            sum += digit/10;
            sum += digit%10;
        }

        int checkDigit = isin[11] - '0';
        if (checkDigit < 0 || checkDigit > 9)
        {
            // Not a digit.
            return false;
        }
        int tensComplement = (sum%10 == 0) ? 0 : ((sum/10) + 1)*10 - sum;
        return checkDigit == tensComplement;
    }
}

Example

string s = "US0378331005";
Debug.Assert(s.IsIsin());

s = "AU0000XVGZA3";
Debug.Assert(s.IsIsin());

s = "GB0002634946";
Debug.Assert(s.IsIsin());

s = null;
Debug.Assert(!s.IsIsin());

s = "";
Debug.Assert(!s.IsIsin());

s = "us0378331005"; // lowercase
Debug.Assert(!s.IsIsin());

s = "US0378331004"; // wrong digit
Debug.Assert(!s.IsIsin());

Author: JP Negri

Submitted on: 31 mrt 2011

Language: C#

Type: System.String

Views: 6299