Skip to main content

Overview

Currencies are fundamental entities in the Currency Exchange API. Each currency is represented by the Currency model, which enforces strict validation rules to ensure data integrity and compliance with international standards.

Currency Model Structure

The Currency class uses an immutable design pattern with a private constructor and a public factory method for creation.
CurrencyExchange.Core/Models/Currency.cs
public class Currency
{
    private Currency(int id, string code, string fullName, string sign)
    {
        Id = id;
        Code = code;
        FullName = fullName;
        Sign = sign;
    }

    public int Id { get; }
    public string Code { get; }
    public string FullName { get; }
    public string Sign { get; }
}

Properties

Id
int
required
Unique identifier for the currency
Code
string
required
ISO 4217 currency code (e.g., “USD”, “EUR”, “RUB”)
FullName
string
required
Full name of the currency (e.g., “US Dollar”, “Euro”)
Sign
string
required
Currency symbol (e.g., ”$”, ”€”, ”₽“)

Creating Currencies

Currencies are created using the static Create method, which performs all necessary validations:
public static Currency Create(int id, string code, string fullName, string sign)
{
    code = code.ToUpperInvariant();

    Validate(code, 3, 5, @"[^A-Z]");
    Validate(fullName, 3, 60, @"[^A-Za-zА-Яа-яЁё() ]");
    Validate(sign, 1, 3, @"[ \n]");

    return new Currency(id, code, fullName, sign);
}
The currency code is automatically converted to uppercase before validation, ensuring consistency across the system.

Validation Rules

The Currency model enforces strict validation rules using regular expressions and length constraints:
Length: 3-5 charactersPattern: Only uppercase letters (A-Z)Regex: [^A-Z] (rejects any non-uppercase letter)Examples:
  • ✅ Valid: “USD”, “EUR”, “RUB”, “GBP”
  • ❌ Invalid: “us” (too short), “usd” (lowercase), “U$D” (special character)
Validate(code, 3, 5, @"[^A-Z]");
Length: 3-60 charactersPattern: Letters (Latin and Cyrillic), parentheses, and spacesRegex: [^A-Za-zА-Яа-яЁё() ] (rejects anything except allowed characters)Examples:
  • ✅ Valid: “US Dollar”, “Euro”, “Российский рубль”
  • ❌ Invalid: ”$” (too short), “Currency@123” (special characters)
Validate(fullName, 3, 60, @"[^A-Za-zА-Яа-яЁё() ]");
Length: 1-3 charactersPattern: No spaces or newlinesRegex: [ \n] (rejects spaces and newlines)Examples:
  • ✅ Valid: ”$”, ”€”, ”₽”, ”£”
  • ❌ Invalid: "" (empty), ”$ ” (contains space)
Validate(sign, 1, 3, @"[ \n]");

Validation Implementation

The validation logic is centralized in a static method that checks for null/empty values, length constraints, and pattern matching:
CurrencyExchange.Core/Models/Currency.cs
public static void Validate(string validateString, int minLength, int maxLength, string pattern)
{
    if (string.IsNullOrEmpty(validateString))
        throw new ArgumentException("Не заполнен один или несколько параметров\n");
    else if (validateString.Length < minLength || validateString.Length > maxLength)
        throw new ArgumentException(
            $"Не корректное количество символов указано для поля {validateString} валюты. Длина строки может быть от {minLength}-х до {maxLength} символов.\n");
    else if (Regex.IsMatch(validateString, pattern, RegexOptions.Compiled))
        throw new ArgumentException($"Не корректные символы в строке {validateString}.\n");
}
The validation method uses RegexOptions.Compiled for improved performance when validating multiple currencies.

ISO 4217 Currency Codes

The Currency Exchange API follows ISO 4217 standards for currency codes. Common examples include:
CodeCurrencySymbol
USDUS Dollar$
EUREuro
RUBRussian Ruble
GBPBritish Pound£
JPYJapanese Yen¥
CNYChinese Yuan¥
While ISO 4217 standard codes are typically 3 characters, the API allows up to 5 characters to accommodate custom or future currency codes.

Error Handling

When validation fails, the Create method throws an ArgumentException with descriptive error messages:
try
{
    var currency = Currency.Create(1, "us", "US Dollar", "$");
}
catch (ArgumentException ex)
{
    // Error: "Не корректное количество символов указано для поля us валюты..."
}

Best Practices

Always Use the Create Method

Never attempt to instantiate Currency directly. Always use the static Create method to ensure all validation rules are applied.

Handle Validation Errors

Wrap currency creation in try-catch blocks to handle validation errors gracefully and provide user-friendly error messages.

Use Standard ISO Codes

Stick to official ISO 4217 currency codes whenever possible to ensure compatibility with external systems and services.

Build docs developers (and LLMs) love