Skip to content

Instantly share code, notes, and snippets.

@altima
Created June 28, 2016 11:39
Show Gist options
  • Save altima/2988c9e6bf2721e033062a1d4252ec95 to your computer and use it in GitHub Desktop.
Save altima/2988c9e6bf2721e033062a1d4252ec95 to your computer and use it in GitHub Desktop.
little iban helper
using System.Linq;
using System.Text.RegularExpressions;
namespace AnyIbanProgramm
{
public class IbanHelper
{
const string StartsWithPattern = @"^[A-Z]{2}[0-9]{2}";
public IbanHelper() { }
private string NormalizeIban(string iban)
{
return iban.Replace(" ", "").Replace("-", "");
}
private string SwapIban(string iban)
{
return iban.Substring(4) + iban.Substring(0, 4);
}
private string Sum(string iban)
{
return iban.Aggregate("", (current, c) => current + (char.IsLetter(c) ? (c - 55).ToString() : c.ToString()));
}
public bool IsCheksumValid(string iban)
{
iban = NormalizeIban(iban);
iban = SwapIban(iban);
var d = decimal.Parse(Sum(iban));
return ((d % 97) == 1);
}
public int CalculateChecksum(string iban)
{
iban = NormalizeIban(iban);
iban = SwapIban(iban).Substring(0, iban.Length - 2) + "00";
var d = decimal.Parse(Sum(iban));
var r = (d % 97);
return (int)(98 - r);
}
public int SliceChecksum(string iban)
{
iban = NormalizeIban(iban);
iban = SwapIban(iban);
return int.Parse(iban.Substring(iban.Length - 2));
}
public bool IsValid(string iban)
{
return (Regex.IsMatch(iban, StartsWithPattern) && IsCheksumValid(iban) && (CalculateChecksum(iban) == SliceChecksum(iban)));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment