using System.Globalization;
using System.Text;
namespace Khaemhat.Core.Validation;
///
/// International Bank Account Numbers (ISO 13616): country, length of the country and the mod-97 check. Spaces and
/// case do not matter.
///
public static class IbanValidator
{
// Lengths of the SEPA countries and their neighbours; other countries are checked for 15-34 characters only.
private static readonly Dictionary Lengths = new(StringComparer.Ordinal)
{
["AD"] = 24, ["AT"] = 20, ["BE"] = 16, ["BG"] = 22, ["CH"] = 21, ["CY"] = 28, ["CZ"] = 24, ["DE"] = 22,
["DK"] = 18, ["EE"] = 20, ["ES"] = 24, ["FI"] = 18, ["FR"] = 27, ["GB"] = 22, ["GI"] = 23, ["GR"] = 27,
["HR"] = 21, ["HU"] = 28, ["IE"] = 22, ["IS"] = 26, ["IT"] = 27, ["LI"] = 21, ["LT"] = 20, ["LU"] = 20,
["LV"] = 21, ["MC"] = 27, ["MT"] = 31, ["NL"] = 18, ["NO"] = 15, ["PL"] = 28, ["PT"] = 25, ["RO"] = 24,
["SE"] = 24, ["SI"] = 19, ["SK"] = 24, ["SM"] = 27, ["VA"] = 22,
};
/// The IBAN without spaces, in capitals.
/// The IBAN as typed.
/// The compact form, or an empty string.
public static string Normalize(string? iban) =>
iban is null ? string.Empty : string.Concat(iban.Where(c => !char.IsWhiteSpace(c))).ToUpperInvariant();
/// The IBAN in groups of four characters, as printed.
/// The IBAN.
/// The printed form.
public static string Format(string? iban)
{
var compact = Normalize(iban);
var builder = new StringBuilder(compact.Length + (compact.Length / 4));
for (var i = 0; i < compact.Length; i++)
{
if (i > 0 && i % 4 == 0)
{
builder.Append(' ');
}
builder.Append(compact[i]);
}
return builder.ToString();
}
/// Whether an IBAN is well formed and its check digits are right.
/// The IBAN, with or without spaces.
/// for a valid IBAN.
public static bool IsValid(string? iban)
{
var value = Normalize(iban);
if (value.Length is < 15 or > 34 || !char.IsAsciiLetterUpper(value[0]) || !char.IsAsciiLetterUpper(value[1])
|| !char.IsAsciiDigit(value[2]) || !char.IsAsciiDigit(value[3]) || !value.All(char.IsAsciiLetterOrDigit))
{
return false;
}
if (Lengths.TryGetValue(value[..2], out var length) && value.Length != length)
{
return false;
}
// Move the first four characters to the end, turn letters into 10-35 and compute mod 97 digit by digit.
var remainder = 0;
foreach (var c in value[4..] + value[..4])
{
var digits = char.IsAsciiDigit(c) ? (c - '0').ToString(CultureInfo.InvariantCulture) : (c - 'A' + 10).ToString(CultureInfo.InvariantCulture);
foreach (var d in digits)
{
remainder = ((remainder * 10) + (d - '0')) % 97;
}
}
return remainder == 1;
}
}
/// GTIN barcodes: EAN-8, UPC-A (12), EAN-13 and GTIN-14, with the mod-10 check digit.
public static class EanValidator
{
/// Whether a barcode has a valid length and check digit.
/// The digits of the barcode.
/// for a valid code.
public static bool IsValid(string? code)
{
var value = code?.Trim() ?? string.Empty;
if (value.Length is not (8 or 12 or 13 or 14) || !value.All(char.IsAsciiDigit))
{
return false;
}
return CheckDigit(value[..^1]) == value[^1] - '0';
}
/// The check digit for the digits of a code without it.
/// The digits before the check digit.
/// The check digit, 0-9.
public static int CheckDigit(string digits)
{
ArgumentNullException.ThrowIfNull(digits);
var sum = 0;
// Weights 3 and 1 alternate starting from the rightmost digit.
for (var i = 0; i < digits.Length; i++)
{
var digit = digits[digits.Length - 1 - i] - '0';
sum += i % 2 == 0 ? digit * 3 : digit;
}
return (10 - (sum % 10)) % 10;
}
}
///
/// E-mail addresses as people type them for invoices and reminders: one @, a local part of up to 64 characters
/// and a domain with at least one dot. Quoted local parts and IP literals are refused on purpose.
///
public static class EmailValidator
{
private const string LocalSpecials = ".!#$%&'*+/=?^_`{|}~-";
/// Whether an address is acceptable.
/// The address.
/// for a valid address.
public static bool IsValid(string? address)
{
var value = address?.Trim() ?? string.Empty;
var at = value.IndexOf('@', StringComparison.Ordinal);
if (value.Length > 254 || at <= 0 || at != value.LastIndexOf('@'))
{
return false;
}
var local = value[..at];
var domain = value[(at + 1)..];
if (local.Length > 64 || local[0] == '.' || local[^1] == '.' || local.Contains("..", StringComparison.Ordinal)
|| !local.All(c => char.IsAsciiLetterOrDigit(c) || LocalSpecials.Contains(c, StringComparison.Ordinal)))
{
return false;
}
var labels = domain.Split('.');
return labels.Length >= 2
&& labels.All(l => l.Length is > 0 and <= 63 && l[0] != '-' && l[^1] != '-' && l.All(c => char.IsLetterOrDigit(c) || c == '-'))
&& labels[^1].Length >= 2 && !labels[^1].All(char.IsAsciiDigit);
}
}