Sign in to follow this  
Followers 0
Bess

IBAN validator

8 posts in this topic

#1 ·  Posted (edited)

Based on : http://en.wikipedia.org/wiki/International_Bank_Account_Number#Validating_the_IBAN

Func _IbanValidate($iban)

;~  1. Parse string, but I don't check if IBAN length is correct as per the country, no need.
    $iban = StringRegExpReplace ( StringUpper($iban), "[^A-Z0-9]", "")

;~      2. Move the four initial characters to the end of the string
    $IBAN_iso = StringLeft($iban, 2) ; If need to know Country code
    $IBAN_key = StringMid($iban, 3, 2) ; next 2 digits
    $IBAN_bban= StringMid($iban, 5)
    $IBAN_Reverse = stringsplit($IBAN_bban & $IBAN_iso & $IBAN_key, "") ; complet reversed Iban to array

;~  3. Replace each letter in the string with two digits, thereby expanding the string, where A = 10, B = 11, ..., Z = 35
    $IBAN_Int = "" ; Iban integer
    For $i = 1 To $IBAN_Reverse[0]
        If StringIsDigit($IBAN_Reverse[$i]) Then
          $IBAN_Int &= $IBAN_Reverse[$i]
        Else
          $IBAN_Int &= Asc($IBAN_Reverse[$i])-55
        EndIf
    Next

;~  4. Interpret the string as a decimal integer and compute the remainder of that number on division by 97
;~     Piece-wise calculation D mod 97
;~     Starting from the leftmost digit of D, construct a number using the first 9 digits and call it N.
;~     Calculate N mod 97. If the result is less than 10, prefix the result with a 0, giving a result in the range 00 to 96.
;~     Construct a new 9-digit N by concatenating above result (step 2) with the next 7 digits of D. If there are fewer than 7 digits remaining in D but at least one, then construct a new N, which will have less than 9 digits, from the above result (step 2) followed by the remaining digits of D
;~     Repeat steps 2–3 until all the digits of D have been processed
;~     The result of the final calculation in step 2 will be D mod 97 = N mod 97.

    $mod_N = Mod(StringLeft($IBAN_Int, 9),97)
    $mod_N = ($mod_N < 10) ? "0" & $mod_N : $mod_N
    $mod_N = Mod($mod_N&StringMid($IBAN_Int, 10, 7),97)
    $mod_N = ($mod_N < 10) ? "0" & $mod_N : $mod_N
    $mod_N = Mod($mod_N&StringMid($IBAN_Int, 17, 7),97)
    $mod_N = ($mod_N < 10) ? "0" & $mod_N : $mod_N
    $IBAN_Validate = Mod(int($mod_N&StringMid($IBAN_Int, 24, 7)),97) == 1

Return $IBAN_Validate
EndFunc

$valide = _IbanValidate("GB82 WEST 1234 5698 7654 32")
ConsoleWrite($valide&@LF)
Edited by Bess

Share this post


Link to post
Share on other sites



I have to find my own verifier, and compare.

I did a similar feature about two years ago.

But at first glance it looks pretty good ;)

mLipok


Signature beginning:   Wondering who uses AutoIT and what it can be used for ?
* GHAPI UDF - modest begining - comunication with GitHub REST API *
ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for other useful stuff click the following button

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST API *

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 - BETA * ADO.au3 UDF SMTP Mailer UDF *

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Best coding practices * 

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * 

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2017-06-04

Share this post


Link to post
Share on other sites

It looks like a good start, but I did notice that ...

$IBAN_Int &= Int(dec(_StringToHex($IBAN_Reverse[$i]))-55)

can be reduced to using StringUpper(), Asc() and then minus 55. I would also add a check (if not done before) that the value is between 10 and 36.


_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 04/09/2015

Share this post


Link to post
Share on other sites

btw.

Welcome to the forum

and please read "How to post code" in my signature

Cheers

mLipok


Signature beginning:   Wondering who uses AutoIT and what it can be used for ?
* GHAPI UDF - modest begining - comunication with GitHub REST API *
ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for other useful stuff click the following button

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST API *

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 - BETA * ADO.au3 UDF SMTP Mailer UDF *

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Best coding practices * 

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * 

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2017-06-04

Share this post


Link to post
Share on other sites

Sorry I couldn't help it.

#include <StringConstants.au3>

Local $UNITED_KINGDOM = 22, _
        $sIBAN = 'GB82 WEST 1234 5698 7654 32'
ConsoleWrite('IsIBAN: ' & _IsIBAN($sIBAN, $UNITED_KINGDOM) & @CRLF)

Func _IsIBAN($sIBAN, $iChars)
    $sIBAN = StringRegExpReplace($sIBAN, '[^A-Za-z0-9]', '')
    ConsoleWrite('Formatted IBAN: ' & $sIBAN & @CRLF)
    Local $iLength = UBound(StringRegExp($sIBAN, '([A-Z0-9])', $STR_REGEXPARRAYGLOBALMATCH))
    ConsoleWrite('Length: ' & $iLength & @CRLF)
    Local $iRemainder = 0
    If $iLength = $iChars Then
        $sIBAN = StringRegExpReplace($sIBAN, '^([A-Z0-9]{4})([A-Z0-9]{' & ($iLength - 4) & '})', '$2$1')
        Local $sChr = '', $sIBANToInt = ''
        For $i = 1 To $iLength
            $sChr = StringMid($sIBAN, $i, 1)
            If Not StringIsInt($sChr) Then
                $sChr = Asc($sChr) - 55
            EndIf
            $sIBANToInt &= $sChr
        Next
        ; Taken from some beautiful C# example: http://iban.saltug.net/
        While (StringLen($sIBANToInt) >= 7)
            $iRemainder = Mod(Int($iRemainder & StringLeft($sIBANToInt, 7)), 97)
            $sIBANToInt = StringTrimLeft($sIBANToInt, 7)
        WEnd
        $iRemainder = Mod(Int($iRemainder & $sIBANToInt), 97)
    EndIf
    Return $iRemainder = 1
EndFunc   ;==>_IsIBAN

_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 04/09/2015

Share this post


Link to post
Share on other sites

so this would be a valid IBAN in both validation routines above

NL-62-DEUT-04485-93815

I am sure payment engines will reject above (similar to payment engines will refuse IBANS with spaces and even SEPA XML XSD's will not allow)

Some code related to validating (just mod 97 on long numbers)

test()

func test()
    consolewrite( 98 - ModLong(IBAN2Number("NL20INGB0001234567"), 97) & @CRLF)
    consolewrite( 98 - ModLong(IBAN2Number("NL94ABNA0458379352"), 97)& @CRLF)
    consolewrite( 98 - ModLong(IBAN2Number("NL 0458379352"), 97) & @CRLF)
    consolewrite( 98 - ModLong(IBAN2Number("NL  ABNA0458379352"), 97)& @CRLF)
    consolewrite( 98 - ModLong(IBAN2Number("NL  ABNA0000000555"), 97)& @CRLF)
 EndFunc
 
func modLong($divident, $divisor)
   const $partLength=6
   while stringlen($divident) > $partLength
         $part=stringleft($divident, $partLength)
         $divident= string(mod($part,$divisor)) & stringmid($divident,$partlength+1)
   WEnd
   return mod($divident,$divisor)    
EndFunc

func IBAN2Number($IBAN)
   local $tStr, $newStr
   $tStr=stringMid($IBAN, 5) & stringLeft($IBAN, 2)
   for $i=1 to stringlen($tStr)
      $tVal=asc(stringmid($tStr,$i,1))
         if $tval>=65 and $tval <=90 Then
            $newStr=$newStr & string($tVal-55)
         Else
            $newStr=$newStr & stringmid($tStr,$i,1)
         EndIf
      Next
   return $newStr & "00"        
endFunc

 
 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0