Tawfir.Toolkit 1.0.19

dotnet add package Tawfir.Toolkit --version 1.0.19
                    
NuGet\Install-Package Tawfir.Toolkit -Version 1.0.19
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Tawfir.Toolkit" Version="1.0.19" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Tawfir.Toolkit" Version="1.0.19" />
                    
Directory.Packages.props
<PackageReference Include="Tawfir.Toolkit" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Tawfir.Toolkit --version 1.0.19
                    
#r "nuget: Tawfir.Toolkit, 1.0.19"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Tawfir.Toolkit@1.0.19
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Tawfir.Toolkit&version=1.0.19
                    
Install as a Cake Addin
#tool nuget:?package=Tawfir.Toolkit&version=1.0.19
                    
Install as a Cake Tool

Tawfir.Toolkit

A comprehensive .NET utilities library containing validation attributes and helper classes for common operations including encryption, calculations, random generation, and validation (KSA ID, Email, etc.).

Installation

dotnet add package Tawfir.Toolkit

Features

  • 🛡️ Card Analyzer - Fraud Prevention: Advanced credit card analysis with Luhn validation, BIN detection, geographic validation, and real-time fraud detection
  • Validation Attributes: KSA ID, Saudi National ID, Non-Saudi Iqama, KSA Mobile Number, Digits Only, Email, Arabic Text, and English Text validation attributes
  • Static Validators: Programmatic validation methods for all validation types
  • Multilingual Text Validation: Arabic, English, Persian, and Turkish text validation with flexible options
  • Content Language Identification: Detect language from text (Arabic, Persian, Turkish, English, Mixed) or from phone number (country calling code)
  • Phone Helpers: Get language code or country name from phone number (e.g. 966 → Arabic, Saudi Arabia)
  • String Extensions: IsDigitsOnly, GetContentLanguage, GetContentLanguageCode, GetLanguageFromPhone, GetCountryFromPhone, MaskExceptLast
  • DataTable Extensions: ToRowDicts() maps each row to a case-insensitive Dictionary<string, object?> for JSON grid APIs (null-safe for DBNull)
  • Helper Classes: Encryption, card expressions, and random generation
  • Regex Patterns: Pre-defined regex patterns for common validations including enhanced Arabic and English patterns

Note: NuGet package includes icon.png for package display

Validation Attributes

KsaId

Use as a validation attribute for any KSA ID (Saudi or Non-Saudi):

using Tawfir.Toolkit.Validator;
using System.ComponentModel.DataAnnotations;

public class UserModel
{
    [KsaId(ErrorMessage = "Invalid KSA ID")]
    public string KsaIdNumber { get; set; }
    
    // Or use with Required attribute
    [Required]
    [KsaId(ErrorMessage = "KSA ID is required and must be valid")]
    public string NationalId { get; set; }
}

The attribute validates:

  • 10-digit format
  • Correct prefix (1 for Saudi, 2 for Non-Saudi)
  • Checksum algorithm validity

SaudiNationalId

Use specifically for Saudi National Id numbers (must start with 1):

using Tawfir.Toolkit.Validator;
using System.ComponentModel.DataAnnotations;

public class SaudiUserModel
{
    [SaudiNationalId(ErrorMessage = "Invalid Saudi National Id")]
    public string SaudiNationalIdNumber { get; set; }
    
    // Or use with Required attribute
    [Required(ErrorMessage = "Saudi National Id is required")]
    [SaudiNationalId(ErrorMessage = "Must be a valid Saudi National Id starting with 1")]
    public string NationalId { get; set; }
}

The SaudiNationalId attribute validates:

  • All standard Civil ID validations (format, checksum)
  • Additional check: Must start with digit 1 (Saudi nationals only)

NonSaudiIqama

Use specifically for Non-Saudi Iqama numbers (must start with 2):

using Tawfir.Toolkit.Validator;
using System.ComponentModel.DataAnnotations;

public class NonSaudiUserModel
{
    [NonSaudiIqama(ErrorMessage = "Invalid Non-Saudi Iqama")]
    public string IqamaNumber { get; set; }
    
    // Or use with Required attribute
    [Required(ErrorMessage = "Non-Saudi Iqama is required")]
    [NonSaudiIqama(ErrorMessage = "Must be a valid Non-Saudi Iqama starting with 2")]
    public string IqamaId { get; set; }
}

The NonSaudiIqama attribute validates:

  • All standard Civil ID validations (format, checksum)
  • Additional check: Must start with digit 2 (Non-Saudi nationals only)

Email

Use for email address validation:

using Tawfir.Toolkit.Validator;
using System.ComponentModel.DataAnnotations;

public class UserModel
{
    [Email(ErrorMessage = "Invalid email address")]
    public string EmailAddress { get; set; }
    
    // Or use with Required attribute
    [Required(ErrorMessage = "Email is required")]
    [Email(ErrorMessage = "Must be a valid email address")]
    public string ContactEmail { get; set; }
}

The Email attribute validates:

  • Valid email format using regex pattern
  • Standard email format requirements

KsaMobileNumber

Use for KSA mobile number validation (05XXXXXXXX format):

using Tawfir.Toolkit.Validator;
using System.ComponentModel.DataAnnotations;

public class UserModel
{
    [KsaMobileNumber(ErrorMessage = "Invalid KSA mobile number")]
    public string MobileNumber { get; set; }
    
    // Or use with Required attribute
    [Required(ErrorMessage = "Mobile number is required")]
    [KsaMobileNumber(ErrorMessage = "Must be a valid KSA mobile number (05XXXXXXXX)")]
    public string ContactMobile { get; set; }
}

The KsaMobileNumber attribute validates:

  • 10-digit format starting with 05
  • Format: 05XXXXXXXX (e.g., 0512345678)

DigitsOnly

Use for validating that a string contains only numeric digits (0-9):

using Tawfir.Toolkit.Validator;
using System.ComponentModel.DataAnnotations;

public class UserModel
{
    [DigitsOnly(ErrorMessage = "Value must contain only digits")]
    public string PinCode { get; set; }
    
    // Or use with Required attribute
    [Required(ErrorMessage = "Account number is required")]
    [DigitsOnly(ErrorMessage = "Account number must contain only digits")]
    public string AccountNumber { get; set; }
    
    // For numeric codes, IDs, etc.
    [DigitsOnly]
    public string VerificationCode { get; set; }
}

The DigitsOnly attribute validates:

  • String contains only numeric digits (0-9)
  • No letters, spaces, special characters, or other symbols allowed
  • Useful for PIN codes, account numbers, numeric IDs, etc.

TextArabic

Use for Arabic text validation with comprehensive Unicode support:

using Tawfir.Toolkit.Validator;
using System.ComponentModel.DataAnnotations;

public class ContentModel
{
    // Basic Arabic text validation
    [TextArabic(ErrorMessage = "يجب أن يكون النص بالعربية فقط")]
    public string Description { get; set; }
    
    // Arabic name validation (letters only, no numbers)
    [TextArabic(NameOnly = true, ErrorMessage = "الاسم يجب أن يكون بالأحرف العربية فقط")]
    public string Name { get; set; }
    
    // Arabic text with diacritics (Tashkeel)
    [TextArabic(AllowDiacritics = true)]
    public string TextWithTashkeel { get; set; }
    
    // Arabic text with Arabic numerals
    [TextArabic(AllowArabicNumerals = true)]
    public string AddressWithNumbers { get; set; }
    
    // Combined with Required
    [Required]
    [TextArabic(NameOnly = true)]
    public string FullName { get; set; }
}

The TextArabic attribute validates:

  • Full Unicode Arabic character support (U+0600-U+06FF and extended ranges)
  • Arabic Supplement, Extended-A, and Presentation Forms
  • Optional diacritics (Tashkeel) support
  • Optional name-only validation (letters only, no numbers)
  • Optional Arabic numerals support (٠-٩, ۰-۹)

Supported Unicode Ranges:

  • Arabic (U+0600-U+06FF)
  • Arabic Supplement (U+0750-U+077F)
  • Arabic Extended-A (U+08A0-U+08FF)
  • Arabic Presentation Forms-A (U+FB50-U+FDFF)
  • Arabic Presentation Forms-B (U+FE70-U+FEFF)
  • Arabic Diacritics (U+064B-U+065F)

TextEnglish

Use for English text validation with various options:

using Tawfir.Toolkit.Validator;
using System.ComponentModel.DataAnnotations;

public class ContentModel
{
    // Basic English text validation (letters only)
    [TextEnglish(ErrorMessage = "Text must be in English only")]
    public string Description { get; set; }
    
    // English name validation (letters and hyphens)
    [TextEnglish(NameOnly = true, ErrorMessage = "Name must contain only English letters")]
    public string FullName { get; set; }
    
    // English text with punctuation
    [TextEnglish(AllowPunctuation = true)]
    public string Comment { get; set; }
    
    // English text with numbers
    [TextEnglish(AllowNumbers = true)]
    public string AddressLine { get; set; }
    
    // Combined with Required
    [Required]
    [TextEnglish(NameOnly = true)]
    public string FirstName { get; set; }
}

The TextEnglish attribute validates:

  • English letters only (A-Z, a-z) by default
  • Optional name validation (allows hyphens for names like "Mary-Jane")
  • Optional punctuation support (.,!?;:'-)
  • Optional alphanumeric support (letters + numbers)

Note: All attributes allow null/empty values by default. Use [Required] if the field is mandatory.

Static Validator Methods

You can also validate programmatically:

using Tawfir.Toolkit.Validator;

// Validate any Civil ID (Saudi or Non-Saudi)
bool isValid = KsaIdValidator.IsValid("1234567890");

// Validate specifically for Saudi National Id (must start with 1)
bool isSaudiValid = KsaSaudiNationalIdValidator.IsValid("1234567890");

// Validate specifically for Non-Saudi Iqama (must start with 2)
bool isNonSaudiValid = KsaNonSaudiIqamaValidator.IsValid("2234567890");

// Validate email address
bool isValidEmail = EmailValidator.IsValid("user@example.com");

// Validate KSA mobile number
bool isValidMobile = KsaMobileNumberValidator.IsValid("0512345678");

// Validate digits-only string
bool isDigitsOnly = DigitsOnlyValidator.IsValid("1234567890"); // true
bool isNotDigitsOnly = DigitsOnlyValidator.IsValid("123abc456"); // false

// Or use string extension method
bool isDigitsOnlyExt = "1234567890".IsDigitsOnly(); // true

// Validate Arabic text
bool isArabicValid = TextArabicValidator.IsValid("مرحبا بك");

// Validate Arabic text with diacritics
bool isArabicWithDiacritics = TextArabicValidator.IsValidWithDiacritics("مَرْحَباً");

// Validate Arabic name (letters only)
bool isArabicName = TextArabicValidator.IsValidName("محمد أحمد");

// Validate Arabic text with Arabic numerals
bool isArabicWithNumerals = TextArabicValidator.IsValidWithArabicNumerals("الشارع ١٢");

// Validate English text
bool isEnglishValid = TextEnglishValidator.IsValid("Hello World");

// Validate English text with punctuation
bool isEnglishWithPunctuation = TextEnglishValidator.IsValidWithPunctuation("Hello, World!");

// Validate English name (with hyphens)
bool isEnglishName = TextEnglishValidator.IsValidName("Mary-Jane Smith");

// Validate English alphanumeric text
bool isEnglishAlphanumeric = TextEnglishValidator.IsValidAlphanumeric("Street 123");

Helper Classes

EncryptionHelper

Encrypt and decrypt strings. Two approaches available:

Option 1: Static Methods (Simple, Quick)

using Tawfir.Toolkit;

// Simple static methods - no DI needed
var encrypted = Helper.Encrypt("sensitive data");
var decrypted = Helper.Decrypt(encrypted);

Option 2: Dependency Injection (Recommended for Production)

using Tawfir.Toolkit.Services;
using Tawfir.Toolkit.Extensions;

// Register in Program.cs - uses strong default encryption key
builder.Services.AddTawfirToolkit();

// Or with custom encryption key (recommended for production)
builder.Services.AddTawfirToolkit(encryptionKey: "YourVeryStrongEncryptionKey123!@#$%");

// Or configure via appsettings.json
// {
//   "Tawfir": {
//     "EncryptionKey": "YourVeryStrongEncryptionKey123!@#$%"
//   }
// }
builder.Services.AddTawfirToolkit();

// Inject in your services
public class PaymentService
{
    private readonly IEncryptionService _encryptionService;
    
    public PaymentService(IEncryptionService encryptionService)
    {
        _encryptionService = encryptionService;
    }
    
    public void ProcessData(string data)
    {
        var encrypted = _encryptionService.Encrypt(data);
        var decrypted = _encryptionService.Decrypt(encrypted);
    }
}

Benefits of DI Approach:

  • Strong default encryption key (32+ characters) - works out of the box
  • ✅ Optional custom encryption key (via parameter or appsettings.json)
  • ✅ Better for testing (can mock IEncryptionService)
  • ✅ Follows dependency injection best practices
  • ✅ Same encryption algorithm as static methods
  • Security validation - enforces strong key requirements (16+ characters if custom key provided)

Security Best Practices:

  • 🔐 Default key is secure (32+ characters), but for production use a custom key per application
  • 🔐 Custom keys should be at least 32 characters (minimum 16)
  • 🔐 Include mix of uppercase, lowercase, numbers, and special characters
  • 🔐 Store keys securely (Azure Key Vault, environment variables, secure configuration)
  • 🔐 Never commit encryption keys to source control
  • 🔐 Use different keys for development, staging, and production

Static Methods:

  • ✅ Simple, no setup required
  • ✅ Quick for simple use cases
  • ✅ Backward compatible
  • ⚠️ Uses default encryption key (not recommended for production)

ExceptionHelper

Extract all exception messages from nested exception chains safely and efficiently:

using Tawfir.Toolkit;

try
{
    // Your code that might throw exceptions
    ProcessPayment();
}
catch (Exception ex)
{
    // Get all nested exception messages
    string allMessages = ex.GetExceptionMessages();
    // Output: "Outer exception ---> Inner exception ---> Deepest exception"
    
    // Log it
    logger.LogError($"Payment failed: {allMessages}");
    
    // Or get full details with stack traces
    string fullDetails = ex.GetExceptionDetails(includeStackTrace: true);
    logger.LogError(fullDetails);
}

Key Features:

Stack Overflow Safe - Iterative approach prevents stack overflow with deep exception chains
AggregateException Support - Captures ALL inner exceptions from parallel operations
High Performance - Efficient string building using List + Join
Max Depth Protection - Configurable depth limit (default: 50) prevents infinite loops
Production Safe - Comprehensive try-catch blocks prevent internal errors during extraction
Full Details Option - Optional stack trace inclusion for debugging

Usage Examples:

// Basic usage - get all messages
string messages = ex.GetExceptionMessages();

// Custom depth limit
string limited = ex.GetExceptionMessages(maxDepth: 10);

// Full details with stack traces
string details = ex.GetExceptionDetails(includeStackTrace: true);

// Handle AggregateException (multiple inner exceptions)
try
{
    await Task.WhenAll(tasks);
}
catch (AggregateException ex)
{
    // Captures ALL task exceptions, not just the first one
    string allErrors = ex.GetExceptionMessages();
    logger.LogError($"Multiple tasks failed: {allErrors}");
}

Real-World Benefits:

  • 🔍 Better Debugging - Never miss inner exception details in logs
  • Better Performance - Faster than manual string concatenation
  • 🛡️ Production Safe - No stack overflow crashes even with 50+ level chains
  • 📊 Complete Logging - Capture everything for analysis and monitoring
  • 🎯 Error Handling Middleware - Perfect for global exception handlers

Perfect For:

  • Error logging systems
  • Exception handling middleware
  • Debugging tools
  • Production monitoring
  • API error responses
  • Application Insights / logging frameworks

Card Analyzer - Fraud Prevention & Security

Advanced credit card analysis and validation for fraud prevention:

using Tawfir.Toolkit.FinTech;

var creditCard = new CreditCard();

// Analyze card for fraud prevention
var cardInfo = creditCard.GetCardInfo("4111111111111111");

// Check validation
if (!cardInfo.IsValid)
{
    // Card failed Luhn algorithm validation - potential fraud
    Console.WriteLine($"Invalid card: {cardInfo.ErrorMessage}");
    return;
}

// Fraud detection checks
if (cardInfo.CardBrand == "Unknown")
{
    // Unknown card brand - suspicious
    // Flag for manual review
}

// Verify card type matches expected
if (cardInfo.CardType == "Debit" && expectedType == "Credit")
{
    // Mismatch detected - potential fraud
}

// Check issuer country for geographic validation
if (cardInfo.IssuerCountry == "Saudi Arabia" && userLocation != "KSA")
{
    // Geographic mismatch - flag for review
}

// Co-badged card detection (Mada + International)
if (cardInfo.IsCoBadged)
{
    // Card can be used on both local (Mada) and international networks
    // Useful for fraud pattern analysis
}

Key Fraud Prevention Features:

Luhn Algorithm Validation - Detects invalid card numbers instantly
BIN (Bank Identification Number) Analysis - Identifies card brand, type, and issuer
Geographic Validation - Verifies issuer country matches transaction location
Card Type Verification - Ensures card type (Credit/Debit) matches expected
Co-badged Card Detection - Identifies dual-network cards for pattern analysis
Format Validation - Validates card number format (13-19 digits)
Real-time Analysis - No external API calls required for basic validation

Fraud Prevention Use Cases:

  1. E-commerce Payment Processing

    • Validate card numbers before processing
    • Detect invalid cards using Luhn algorithm
    • Flag suspicious cards for manual review
  2. Geographic Fraud Detection

    • Verify issuer country matches user location
    • Detect cross-border fraud patterns
    • Validate Mada cards for Saudi transactions
  3. Card Type Validation

    • Ensure card type matches transaction type
    • Detect debit cards used for credit-only services
    • Validate corporate vs personal cards
  4. BIN Analysis

    • Identify card issuer and brand
    • Detect unknown or suspicious BINs
    • Track fraud patterns by card brand
  5. Real-time Fraud Scoring

    • Combine multiple validation checks
    • Create fraud risk scores
    • Automatically flag high-risk transactions

Supported Card Brands:

  • Visa
  • Mastercard
  • American Express
  • Discover
  • JCB
  • Diners Club
  • Maestro
  • UnionPay
  • Mada (Saudi Arabia) - with automatic bank identification
  • Co-badged cards (Mada + Visa/Mastercard)

Example: Complete Fraud Prevention Check

public bool IsSuspiciousCard(string cardNumber, string userCountry)
{
    var creditCard = new CreditCard();
    var cardInfo = creditCard.GetCardInfo(cardNumber);
    
    // Basic validation
    if (!cardInfo.IsValid)
        return true; // Invalid card = fraud
    
    // Unknown brand
    if (cardInfo.CardBrand == "Unknown")
        return true; // Suspicious
    
    // Geographic mismatch for Mada cards
    if (cardInfo.CardBrand == "Mada" && userCountry != "Saudi Arabia")
        return true; // Mada cards should be used in KSA
    
    // Check if issuer country matches user location
    if (!string.IsNullOrEmpty(cardInfo.IssuerCountry) && 
        cardInfo.IssuerCountry != userCountry)
    {
        // Flag for additional verification
        return true;
    }
    
    return false; // Card appears legitimate
}

CardExpression

Card number processing and tokenization:

using Tawfir.Toolkit.Helpers;

string cardToken = CardExpression.GetCardToken(cardNo, expiryDate);
string cardNumber = CardExpression.GetCardNumber(cardToken);

RandomGen

Generate random strings and numbers:

using Tawfir.Toolkit.Helpers;

string randomString = RandomGen.String(length: 10);
string numbersOnly = RandomGen.String(length: 6, NumbersOnly: true);
int randomInt = RandomGen.INT(from: 1, to: 100);

String Extensions

Extension methods for string operations:

using Tawfir.Toolkit;

// Check if string contains only digits (0-9)
string phoneNumber = "0512345678";
bool isValid = phoneNumber.IsDigitsOnly(); // Returns true

string invalid = "123abc456";
bool isInvalid = invalid.IsDigitsOnly(); // Returns false

// Use in conditional statements
if (userInput.IsDigitsOnly())
{
    // Process numeric input
}

// Identify content language (Arabic, English, Mixed, or Unknown)
using Tawfir.Toolkit.Models;

ContentLanguage lang1 = "مرحبا بك".GetContentLanguage();       // ContentLanguage.Arabic
ContentLanguage lang2 = "Hello World".GetContentLanguage();    // ContentLanguage.English
ContentLanguage lang3 = "Hello عالم".GetContentLanguage();   // ContentLanguage.Mixed
ContentLanguage lang4 = "123".GetContentLanguage();            // ContentLanguage.Unknown
ContentLanguage lang5 = "چطور".GetContentLanguage();           // ContentLanguage.Persian (contains چ)

if (userInput.GetContentLanguage() == ContentLanguage.Arabic)
{
    // Handle Arabic content
}

Available Methods:

  • IsDigitsOnly() - Returns true if the string contains only numeric digits (0-9), false otherwise. Handles null/empty strings safely.
  • GetContentLanguage() - Returns ContentLanguage enum. Use GetContentLanguageCode() to get a language code instead.
  • GetContentLanguageCode() - Returns language code string: "ar", "en", "fa", "tr", "mixed", or "unknown".
  • GetLanguageFromPhone() - Returns language code from phone number by country calling code (e.g. 966 → "ar").
  • GetCountryFromPhone() - Returns country name from phone number (e.g. 966 → "Saudi Arabia").
  • MaskExceptLast(numberOfVisibleChars, maskChar) - Masks all characters except the last N (e.g. "0512345678".MaskExceptLast(4, '*')"******5678").

DataTable extensions (JSON grids)

Turn a System.Data.DataTable into a list of dictionaries suitable for System.Text.Json / ASP.NET Core responses (e.g. paged SQL results):

using System.Data;
using Tawfir.Toolkit;

DataTable table = /* from ADO.NET, SqlDataAdapter, etc. */;
var rows = table.ToRowDicts();
// rows: List<Dictionary<string, object?>> — column names are keys (case-insensitive), DBNull → null
return Results.Ok(new { items = rows, totalCount = 42 });

ToRowDicts() behavior

  • One dictionary per row; keys match column names.
  • Key comparison is ordinal ignore case (stable for JSON clients).
  • DBNull values become null in the dictionary.

Content Language Identification

Identify the language of text content (Arabic, Persian, Turkish, English, Mixed, or Unknown) using script analysis. Persian is distinguished from Arabic by پ, چ, ژ, گ. Turkish is distinguished from English by İ, ı, ğ, Ğ, ü, Ü, ö, Ö, ç, Ç, ş, Ş.

using Tawfir.Toolkit;
using Tawfir.Toolkit.Helpers;
using Tawfir.Toolkit.Models;

// Static helper
ContentLanguage lang = ContentLanguageIdentifier.Identify("مرحبا");   // Arabic
ContentLanguage lang2 = ContentLanguageIdentifier.Identify("چطور");   // Persian
ContentLanguage lang3 = ContentLanguageIdentifier.Identify("Türkçe");  // Turkish (contains ü, ç)
ContentLanguage lang4 = ContentLanguageIdentifier.Identify("Hello");   // English

// String extension
ContentLanguage lang5 = "نص عربي".GetContentLanguage();     // ContentLanguage.Arabic
ContentLanguage lang6 = "پدر".GetContentLanguage();         // ContentLanguage.Persian
ContentLanguage lang7 = "Türkçe".GetContentLanguage();      // ContentLanguage.Turkish (ü, ç)
ContentLanguage lang8 = "English text".GetContentLanguage();  // ContentLanguage.English
ContentLanguage lang9 = "Mixed نص".GetContentLanguage();    // ContentLanguage.Mixed

ContentLanguage enum: Unknown, Arabic, English, Mixed, Persian, Turkish

Language codes (ISO 639-1 style): Return language code instead of enum:

using Tawfir.Toolkit;
using Tawfir.Toolkit.Helpers;
using Tawfir.Toolkit.Models;

// Return language code: "ar", "en", "fa", "tr", "mixed", "unknown"
string code = "مرحبا".GetContentLanguageCode();       // "ar"
string code2 = "Hello".GetContentLanguageCode();     // "en"
string code3 = "چطور".GetContentLanguageCode();      // "fa"
string code4 = "Türkçe".GetContentLanguageCode();    // "tr"
string code5 = "Hello عالم".GetContentLanguageCode(); // "mixed"

// Static helper
string code6 = ContentLanguageIdentifier.IdentifyLanguageCode("مرحبا"); // "ar"

// From enum to code
string code7 = ContentLanguage.Arabic.ToLanguageCode();  // "ar"
string code8 = ContentLanguage.Turkish.ToLanguageCode(); // "tr"
Language Code
Arabic ar
English en
Persian fa
Turkish tr
Mixed mixed
Unknown unknown

Language from phone number

Get language code from phone number using country calling code (e.g. 966 → Arabic):

using Tawfir.Toolkit;
using Tawfir.Toolkit.Helpers;

// Static helper
string lang = PhoneLanguageHelper.GetLanguageFromPhone("+966512345678");  // "ar" (Saudi)
string lang2 = PhoneLanguageHelper.GetLanguageFromPhone("0512345678");    // "ar" (KSA local)
string lang3 = PhoneLanguageHelper.GetLanguageFromPhone("+971501234567"); // "ar" (UAE)
string lang4 = PhoneLanguageHelper.GetLanguageFromPhone("+905321234567");  // "tr" (Turkey)
string lang5 = PhoneLanguageHelper.GetLanguageFromPhone("+989121234567"); // "fa" (Iran)
string lang6 = PhoneLanguageHelper.GetLanguageFromPhone("+14155551234");   // "en" (USA)
string lang7 = PhoneLanguageHelper.GetLanguageFromPhone("+923001234567");   // "ur" (Pakistan)
string lang8 = PhoneLanguageHelper.GetLanguageFromPhone("+919876543210");   // "hi" (India)
string lang9 = PhoneLanguageHelper.GetLanguageFromPhone("+33612345678");     // "fr" (France)
string lang10 = PhoneLanguageHelper.GetLanguageFromPhone("+4915123456789");  // "de" (Germany)
string lang11 = PhoneLanguageHelper.GetLanguageFromPhone("+8613812345678");  // "zh" (China)
string lang12 = PhoneLanguageHelper.GetLanguageFromPhone("+79161234567");    // "ru" (Russia)

// String extension
string code = "00966512345678".GetLanguageFromPhone(); // "ar"

Get country from phone number:

string country = PhoneLanguageHelper.GetCountryFromPhone("+966512345678");  // "Saudi Arabia"
string country2 = PhoneLanguageHelper.GetCountryFromPhone("0512345678");   // "Saudi Arabia" (KSA local)
string country3 = PhoneLanguageHelper.GetCountryFromPhone("+971501234567"); // "United Arab Emirates"
string country4 = PhoneLanguageHelper.GetCountryFromPhone("+905321234567");  // "Turkey"

// String extension
string country5 = "00966512345678".GetCountryFromPhone(); // "Saudi Arabia"

Supported formats: +966..., 00966..., 966..., and KSA local 05xxxxxxxx. Language returns e.g. "ar", "en", "fa", "tr", "ur", "hi", "fr", "de", "zh", "ru" or "unknown". Country returns full name (e.g. "Saudi Arabia") or "Unknown".

Regex Patterns (RegexExp)

Pre-defined regex patterns for common validations:

using Tawfir.Toolkit.Models;
using System.Text.RegularExpressions;

// Civil ID patterns
Regex.IsMatch(id, RegexExp.Saudi);        // Saudi National ID (starts with 1)
Regex.IsMatch(id, RegexExp.NonSaudi);     // Non-Saudi Iqama (starts with 2)
Regex.IsMatch(id, RegexExp.CivilId);      // Any Civil ID (starts with 1 or 2)

// Financial patterns
Regex.IsMatch(iban, RegexExp.IBAN);       // Saudi IBAN format

// Contact patterns
Regex.IsMatch(mobile, RegexExp.Mobile);   // Saudi mobile (05XXXXXXXX)
Regex.IsMatch(phone, RegexExp.Phone);     // Saudi phone (01XXXXXXXX)

// Security patterns
Regex.IsMatch(password, RegexExp.Password);  // Strong password
Regex.IsMatch(pin, RegexExp.PIN);            // 6-character PIN
Regex.IsMatch(pin, RegexExp.PINCC);          // 4-character PIN
Regex.IsMatch(otp, RegexExp.OTP);            // OTP code

// Date patterns
Regex.IsMatch(date, RegexExp.Date_G);     // Gregorian date (DD/MM/YYYY)
Regex.IsMatch(date, RegexExp.Date_H);    // Hijri date (DD/MM/YYYY)

// Text patterns
Regex.IsMatch(text, RegexExp.Alphabetical);     // Alphabetical with Arabic support
Regex.IsMatch(text, RegexExp.Alphabetical_En);   // English only
Regex.IsMatch(text, RegexExp.Alphabetical_AR);   // Arabic with numbers (basic)

// Enhanced Arabic patterns
Regex.IsMatch(text, RegexExp.Arabic_Only);              // Full Arabic Unicode support
Regex.IsMatch(text, RegexExp.Arabic_Letters_Only);      // Arabic letters + Arabic numerals
Regex.IsMatch(text, RegexExp.Arabic_With_Diacritics);   // Arabic with Tashkeel marks
Regex.IsMatch(text, RegexExp.Arabic_Name);              // Arabic names (letters only)

// Enhanced English patterns
Regex.IsMatch(text, RegexExp.English_Only);             // English letters only
Regex.IsMatch(text, RegexExp.English_Letters_Only);     // English letters + numbers
Regex.IsMatch(text, RegexExp.English_With_Punctuation); // English with punctuation
Regex.IsMatch(text, RegexExp.English_Name);             // English names (letters + hyphens)

Arabic Text Validation - Detailed Guide

The toolkit provides comprehensive Arabic text validation with multiple options:

Available Patterns

Pattern Description Use Case
Arabic_Only Full Unicode Arabic support including all presentation forms General Arabic content, mixed text
Arabic_Letters_Only Arabic letters + Arabic-Indic digits (٠-٩, ۰-۹) Addresses, descriptions with numbers
Arabic_With_Diacritics Arabic text with Tashkeel marks (َ ِ ُ ً ٍ ٌ) Quranic text, formal documents
Arabic_Name Arabic letters only, no numbers Names of people, cities, organizations

Usage Examples

using Tawfir.Toolkit.Validator;

// Validate general Arabic text
var text1 = "مرحبا بك في السعودية";
var isValid1 = TextArabicValidator.IsValid(text1); // true

// Validate Arabic name (no numbers allowed)
var name = "محمد أحمد";
var isValidName = TextArabicValidator.IsValidName(name); // true

// Validate text with Arabic numerals
var address = "الشارع ١٢ حي النخيل";
var isValidAddr = TextArabicValidator.IsValidWithArabicNumerals(address); // true

// Validate text with diacritics
var quranicText = "بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ";
var isValidQuran = TextArabicValidator.IsValidWithDiacritics(quranicText); // true

Common Use Cases

1. User Names (Arabic only)

[TextArabic(NameOnly = true)]
public string FullName { get; set; }

2. Addresses (Arabic with numbers)

[TextArabic(AllowArabicNumerals = true)]
public string Address { get; set; }

3. Religious or Formal Text (with diacritics)

[TextArabic(AllowDiacritics = true)]
public string FormalText { get; set; }

4. General Arabic Content

[TextArabic]
public string Description { get; set; }

English Text Validation - Detailed Guide

The toolkit provides comprehensive English text validation with multiple options:

Available Patterns

Pattern Description Use Case
English_Only English letters only (A-Z, a-z) Pure text content, descriptions
English_Letters_Only English letters + digits (0-9) Addresses, alphanumeric codes
English_With_Punctuation English letters, numbers, and punctuation (.,!?;:'-) Sentences, comments, paragraphs
English_Name English letters and hyphens Person names (Mary-Jane, Jean-Claude)

Usage Examples

using Tawfir.Toolkit.Validator;

// Validate general English text
var text1 = "Hello World";
var isValid1 = TextEnglishValidator.IsValid(text1); // true

// Validate English name with hyphen
var name = "Mary-Jane Smith";
var isValidName = TextEnglishValidator.IsValidName(name); // true

// Validate text with alphanumeric
var address = "Street 123 Building A";
var isValidAddr = TextEnglishValidator.IsValidAlphanumeric(address); // true

// Validate text with punctuation
var sentence = "Hello, World! How are you?";
var isValidSentence = TextEnglishValidator.IsValidWithPunctuation(sentence); // true

Common Use Cases

1. User Names (English only)

[TextEnglish(NameOnly = true)]
public string FullName { get; set; }

2. Addresses (English with numbers)

[TextEnglish(AllowNumbers = true)]
public string Address { get; set; }

3. Comments and Reviews (with punctuation)

[TextEnglish(AllowPunctuation = true)]
public string Comment { get; set; }

4. General English Content

[TextEnglish]
public string Description { get; set; }

Namespaces

  • Tawfir.Toolkit - Core helpers (ExceptionHelper, EncryptionHelper), string extensions (IsDigitsOnly, GetContentLanguage, GetContentLanguageCode, GetLanguageFromPhone, GetCountryFromPhone, MaskExceptLast), DataTable extension ToRowDicts() (DataTableExtensions)
  • Tawfir.Toolkit.Validator - Validation attributes and static validators (KSA ID, Email, DigitsOnly, TextArabic, TextEnglish, etc.)
  • Tawfir.Toolkit.Helpers - ContentLanguageIdentifier, PhoneLanguageHelper, ContentLanguageExtensions, StringExtensions, RandomGen, CardExpression
  • Tawfir.Toolkit.Models - ContentLanguage enum, RegexExp patterns
  • Tawfir.Toolkit.Services - IEncryptionService and EncryptionService
  • Tawfir.Toolkit.Extensions - DI registration (AddTawfirToolkit)
  • Tawfir.Toolkit.FinTech - CreditCard, Loan, and financial utilities

Requirements

  • .NET 10.0 or higher (SDK-style projects; TargetFramework net10.0)

License

Current Version (Free)

  • The current version of Tawfir.Toolkit is fully free and available for use without any restrictions.
  • All existing features, including validation, encryption, content language identification, phone helpers, and more, are available at no cost.

Future Plans (Q1 2026)

  • Starting in the first quarter of 2026, we will introduce new premium features and enhanced support that will be available under a paid license.
  • The current free version will continue to be available and maintained.
  • Paid plans will include:
    • Advanced features and capabilities
    • Priority support and technical assistance
    • Enhanced monitoring and analytics
    • Additional enterprise-grade features

Note: Existing users of the free version can continue using it without any changes. The transition to paid features is optional and only applies to new premium capabilities.

Support

For support, please contact:

  • Email: info@waelelazizy.com
  • KSA: 0553373500
  • Bahrain: 00973 33030730

Author

wael EL azizy - waelelazizy.com

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.19 140 5/3/2026
1.0.18 208 4/6/2026
1.0.17 115 4/5/2026
1.0.16 155 3/27/2026
1.0.15 129 3/15/2026
1.0.14 108 3/15/2026
1.0.13 115 3/15/2026
1.0.12 258 1/15/2026
1.0.11 119 1/14/2026
1.0.10 217 1/4/2026
1.0.9 315 12/16/2025
1.0.8 218 12/5/2025
1.0.7 227 11/3/2025
1.0.6 228 11/3/2025
1.0.5 242 11/3/2025
1.0.4 225 11/3/2025
1.0.3 232 11/3/2025
1.0.2 231 11/3/2025

Initial release with validation attributes and helper classes