A comprehensive .NET utilities library containing validation attributes and helper classes for common operations including encryption, random generation, multilingual text validation (Arabic, English), and KSA-specific validators (National ID, Iqama, Email).
$ dotnet add package Tawfir.ToolkitA comprehensive .NET utilities library containing validation attributes and helper classes for common operations including encryption, calculations, random generation, and validation (KSA ID, Email, etc.).
dotnet add package Tawfir.Toolkit
Note: NuGet package includes icon.png for package display
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:
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:
1 (Saudi nationals only)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:
2 (Non-Saudi nationals only)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:
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:
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:
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:
Supported Unicode Ranges:
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:
Note: All attributes allow null/empty values by default. Use [Required] if the field is mandatory.
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");
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:
Security Best Practices:
Static Methods:
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:
Perfect For:
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:
E-commerce Payment Processing
Geographic Fraud Detection
Card Type Validation
BIN Analysis
Real-time Fraud Scoring
Supported Card Brands:
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
}
Card number processing and tokenization:
using Tawfir.Toolkit.Helpers;
string cardToken = CardExpression.GetCardToken(cardNo, expiryDate);
string cardNumber = CardExpression.GetCardNumber(cardToken);
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);
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
}
Available Methods:
IsDigitsOnly() - Returns true if the string contains only numeric digits (0-9), false otherwise. Handles null/empty strings safely.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)
The toolkit provides comprehensive Arabic text validation with multiple options:
| 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 |
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
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; }
The toolkit provides comprehensive English text validation with multiple options:
| 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) |
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
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; }
Tawfir.Toolkit - Core helper classes (ExceptionHelper, EncryptionHelper static methods)Tawfir.Toolkit.Validator - Validation attributes and static validatorsTawfir.Toolkit.Helpers - Helper classes for common operationsTawfir.Toolkit.Models - Models and constants (e.g., RegexExp)Tawfir.Toolkit.Services - Dependency injection services (IEncryptionService)Tawfir.Toolkit.Extensions - Extension methods for DI registrationTawfir.Toolkit.FinTech - Financial and credit card utilitiesCurrent Version (Free)
Future Plans (Q1 2026)
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.
For support, please contact:
wael EL azizy - waelelazizy.com