

 This page uses content from Wikipedia. The original article was at IBAN. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)



The   International Bank Account Number (IBAN)   is an internationally agreed means of identifying bank accounts across national borders with a reduced risk of propagating transcription errors.

The IBAN consists of up to 34 alphanumeric characters:

   first the two-letter ISO 3166-1 alpha-2 country code, 
   then two check digits, and 
   finally a country-specific Basic Bank Account Number (BBAN). 


The check digits enable a sanity check of the bank account number to confirm its integrity even before submitting a transaction.



Task

Validate the following fictitious IBAN:    GB82 WEST 1234 5698 7654 32 



Details of the algorithm can be found on the Wikipedia page.




--
-- demo\rosetta\IBAN.exw
-- =====================
--
constant nations = {{"AD",24},  -- Andorra
                    -- (full list in distro)
                    {"CH",21},  -- Switzerland
                    {"GB",22},  -- United Kingdom
                    {"SA",24},  -- Saudi Arabia 
                    {"XK",20}}  -- Kosovo
 
constant {countries,lengths} = columnize(nations)
 
function iban(string code)
-- This routine does and should reject codes containing spaces etc.
-- Use iban_s() below for otherwise.
    integer country = find(code[1..2],countries)
    if country!=0
    and length(code)=lengths[country] then
        code = code[5..$]&code[1..4]
        integer c = 0
        for i=1 to length(code) do
            integer ch=code[i]
            if ch>='0' and ch<='9' then
                c = c*10+ch-'0'
            elsif ch>='A' and ch<='Z' then
                c = c*100+ch-55
            else
                return false
            end if
            c = mod(c,97)
        end for
        return c=1
    end if
    return false
end function
 
function iban_s(string code)
-- strips any embedded spaces and hyphens before validating.
    code = substitute_all(code,{" ","-"},{"",""})
    return iban(code)
end function
 
procedure test(string code, bool expected)
    bool valid = iban_s(code)
    string state
    if valid=expected then
        state = iff(valid?"ok":"invalid (as expected)")
    else
        state = iff(valid?"OK!!":"INVALID!!")&" (NOT AS EXPECTED)"
    end if
    printf(1,"%-34s :%s\n",{code,state})
end procedure
 
test("GB82 WEST 1234 5698 7654 32",true)
test("GB82 TEST 1234 5698 7654 32",false)
test("GB81 WEST 1234 5698 7654 32",false)
test("SA03 8000 0000 6080 1016 7519",true)
test("CH93 0076 2011 6238 5295 7",true)
