50 lines
1.4 KiB
C#
50 lines
1.4 KiB
C#
|
|
using System.ComponentModel.DataAnnotations;
|
|
using System.Numerics;
|
|
using System.Text;
|
|
using System.Text.RegularExpressions;
|
|
|
|
namespace NejCommon.Validation;
|
|
|
|
public class IbanAttribute : RegexAttribute{
|
|
public const string IbanRegex = @"^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$";
|
|
public IbanAttribute() : base(IbanRegex,"CZ4622500000000104816258"){
|
|
|
|
}
|
|
|
|
protected override ValidationResult IsValid(object value, ValidationContext ctx)
|
|
{
|
|
if (value is null)
|
|
return ValidationResult.Success!;
|
|
var res = base.IsValid(value, ctx);
|
|
if (res != ValidationResult.Success)
|
|
return res;
|
|
|
|
string iban = value as string;
|
|
|
|
string rearranged = iban.Substring(4) + iban.Substring(0, 4);
|
|
|
|
// Convert letters to numbers (A=10, B=11, ..., Z=35)
|
|
StringBuilder numericIban = new StringBuilder();
|
|
foreach (char ch in rearranged)
|
|
{
|
|
if (char.IsLetter(ch))
|
|
{
|
|
int charVal = ch - 'A' + 10;
|
|
numericIban.Append(charVal);
|
|
}
|
|
else
|
|
{
|
|
numericIban.Append(ch);
|
|
}
|
|
}
|
|
|
|
// Convert to BigInteger and compute mod 97
|
|
BigInteger ibanNumber = BigInteger.Parse(numericIban.ToString());
|
|
|
|
if(ibanNumber % 97 == 1)
|
|
return ValidationResult.Success;
|
|
else
|
|
return new ValidationResult("Invalid checksum of IBAN");
|
|
}
|
|
} |