Files
eatvio_app/lib/core/utils/validation_utils.dart
2026-01-29 15:49:13 +03:00

103 lines
4.3 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'package:eatvio_app/core/constants/app_constants.dart';
/// Утилиты для валидации
class ValidationUtils {
/// Валидация email
static bool isValidEmail(String email) {
if (email.isEmpty) return false;
final regex = RegExp(AppConstants.emailRegex);
return regex.hasMatch(email);
}
/// Валидация телефона
static bool isValidPhone(String phone) {
if (phone.isEmpty) return false;
final regex = RegExp(AppConstants.phoneRegex);
return regex.hasMatch(phone);
}
/// Нормализация номера телефона (+79991234455)
static String normalizePhone(String phone) {
if (phone.isEmpty) return '';
final digits = phone.replaceAll(RegExp(r'[^\d]'), '');
if (digits.isEmpty) return '';
String normalized = digits;
if (digits.startsWith('8')) {
normalized = '7${digits.substring(1)}';
} else if (digits.length == 10) {
normalized = '7$digits';
}
return '+$normalized';
}
/// Валидация URL
static bool isValidUrl(String url) {
if (url.isEmpty) return false;
final regex = RegExp(AppConstants.urlRegex);
return regex.hasMatch(url);
}
/// Валидация длины текста
static bool isValidTextLength(String text, {int? maxLength}) {
final length = maxLength ?? AppConstants.maxTextLength;
return text.length <= length;
}
/// Валидация длины заголовка
static bool isValidTitleLength(String title) {
return title.isNotEmpty && title.length <= AppConstants.maxTitleLength;
}
/// Валидация длины описания
static bool isValidDescriptionLength(String description) {
return description.length <= AppConstants.maxDescriptionLength;
}
/// Валидация пароля
static bool isValidPassword(String password) {
// Минимум 8 символов, хотя бы одна буква и одна цифра
if (password.length < 8) return false;
final hasLetter = RegExp(r'[a-zA-Z]').hasMatch(password);
final hasDigit = RegExp(r'[0-9]').hasMatch(password);
return hasLetter && hasDigit;
}
/// Валидация имени пользователя
static bool isValidUsername(String username) {
// От 3 до 20 символов, только буквы, цифры и подчеркивания
if (username.length < 3 || username.length > 20) return false;
final regex = RegExp(r'^[a-zA-Z0-9_]+$');
return regex.hasMatch(username);
}
/// Получение сообщения об ошибке валидации
static String? getValidationErrorMessage(String? value, ValidationType type) {
if (value == null || value.isEmpty) {
return 'Поле не может быть пустым';
}
switch (type) {
case ValidationType.email:
return isValidEmail(value) ? null : 'Введите корректный email';
case ValidationType.phone:
return isValidPhone(value) ? null : 'Введите корректный номер телефона';
case ValidationType.url:
return isValidUrl(value) ? null : 'Введите корректный URL';
case ValidationType.password:
return isValidPassword(value) ? null : 'Пароль должен содержать минимум 8 символов, включая буквы и цифры';
case ValidationType.username:
return isValidUsername(value) ? null : 'Имя пользователя должно содержать от 3 до 20 символов (буквы, цифры, подчеркивания)';
case ValidationType.title:
return isValidTitleLength(value) ? null : 'Заголовок не может быть пустым и должен содержать не более ${AppConstants.maxTitleLength} символов';
case ValidationType.description:
return isValidDescriptionLength(value) ? null : 'Описание не может содержать более ${AppConstants.maxDescriptionLength} символов';
case ValidationType.text:
return isValidTextLength(value) ? null : 'Текст не может содержать более ${AppConstants.maxTextLength} символов';
}
}
}
/// Типы валидации
enum ValidationType { email, phone, url, password, username, title, description, text }