/
VFlov
/
NotificationService_1
Обзор
Документация
Войти
/
VFlov
/
NotificationService_1
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/Shared/NotificationService.Shared/Validators/NotificationValidator.cs
153 строки
5 KB
VFlov
Update
25 дек 2025, 21:02
25 дек 2025, 21:02
cf3965d
Код
Авторство
О чём код?
using NotificationService.Shared.DTOs; using NotificationService.Shared.Models; using System.ComponentModel.DataAnnotations; using System.Text.RegularExpressions; namespace NotificationService.Shared.Validators; /// <summary> /// Валидатор для запросов уведомлений /// </summary> public static class NotificationValidator { private static readonly Regex EmailRegex = new(@"^[^@\s]+@[^@\s]+\.[^@\s]+$", RegexOptions.Compiled); private static readonly Regex PhoneRegex = new(@"^\+?[1-9]\d{1,14}$", RegexOptions.Compiled); /// <summary> /// Валидация запроса на отправку уведомления /// </summary> public static ValidationResult ValidateRequest(SendNotificationRequest request) { var errors = new List<string>(); // Проверка получателя if (string.IsNullOrWhiteSpace(request.Recipient)) { errors.Add("Recipient is required"); } else { switch (request.Type) { case NotificationType.Email: if (!IsValidEmail(request.Recipient)) { errors.Add($"Invalid email format: {request.Recipient}"); } break; case NotificationType.Sms: if (!IsValidPhoneNumber(request.Recipient)) { errors.Add($"Invalid phone number format: {request.Recipient}"); } break; case NotificationType.Push: // Push токены обычно длинные строки, проверяем минимальную длину if (request.Recipient.Length < 10) { errors.Add($"Invalid push token format: {request.Recipient}"); } break; default: errors.Add($"Unsupported notification type: {request.Type}"); break; } } // Проверка контента if (string.IsNullOrWhiteSpace(request.Content)) { errors.Add("Content is required"); } else if (request.Content.Length > 10000) { errors.Add("Content is too long (max 10000 characters)"); } // Проверка темы (для Email и Push) if (request.Type == NotificationType.Email || request.Type == NotificationType.Push) { if (string.IsNullOrWhiteSpace(request.Subject)) { errors.Add("Subject is required for Email and Push notifications"); } else if (request.Subject.Length > 500) { errors.Add("Subject is too long (max 500 characters)"); } } // Проверка метаданных if (request.Metadata != null) { foreach (var (key, value) in request.Metadata) { if (string.IsNullOrWhiteSpace(key)) { errors.Add("Metadata keys cannot be empty"); } if (value == null) { errors.Add($"Metadata value for key '{key}' cannot be null"); } } } return new ValidationResult { IsValid = errors.Count == 0, Errors = errors }; } /// <summary> /// Проверка валидности email адреса /// </summary> public static bool IsValidEmail(string email) { if (string.IsNullOrWhiteSpace(email)) return false; try { return EmailRegex.IsMatch(email); } catch { return false; } } /// <summary> /// Проверка валидности номера телефона (E.164 format) /// </summary> public static bool IsValidPhoneNumber(string phoneNumber) { if (string.IsNullOrWhiteSpace(phoneNumber)) return false; try { return PhoneRegex.IsMatch(phoneNumber); } catch { return false; } } } /// <summary> /// Результат валидации /// </summary> public class ValidationResult { public bool IsValid { get; set; } public List<string> Errors { get; set; } = new(); public string GetErrorMessage() => string.Join("; ", Errors); }