67 lines
1.6 KiB
Dart
67 lines
1.6 KiB
Dart
/// Utility class for input validation
|
|
class Validators {
|
|
Validators._();
|
|
|
|
/// Validate email
|
|
static String? validateEmail(String? value) {
|
|
if (value == null || value.isEmpty) {
|
|
return 'Email is required';
|
|
}
|
|
final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
|
|
if (!emailRegex.hasMatch(value)) {
|
|
return 'Enter a valid email';
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// Validate required field
|
|
static String? validateRequired(String? value, {String? fieldName}) {
|
|
if (value == null || value.isEmpty) {
|
|
return '${fieldName ?? 'This field'} is required';
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// Validate price
|
|
static String? validatePrice(String? value) {
|
|
if (value == null || value.isEmpty) {
|
|
return 'Price is required';
|
|
}
|
|
final price = double.tryParse(value);
|
|
if (price == null) {
|
|
return 'Enter a valid price';
|
|
}
|
|
if (price <= 0) {
|
|
return 'Price must be greater than 0';
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// Validate quantity
|
|
static String? validateQuantity(String? value) {
|
|
if (value == null || value.isEmpty) {
|
|
return 'Quantity is required';
|
|
}
|
|
final quantity = int.tryParse(value);
|
|
if (quantity == null) {
|
|
return 'Enter a valid quantity';
|
|
}
|
|
if (quantity < 0) {
|
|
return 'Quantity cannot be negative';
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// Validate phone number
|
|
static String? validatePhone(String? value) {
|
|
if (value == null || value.isEmpty) {
|
|
return 'Phone number is required';
|
|
}
|
|
final phoneRegex = RegExp(r'^\+?[\d\s-]{10,}$');
|
|
if (!phoneRegex.hasMatch(value)) {
|
|
return 'Enter a valid phone number';
|
|
}
|
|
return null;
|
|
}
|
|
}
|