Files
family_budget/frontend/src/utils/validation.ts
2026-01-29 15:17:54 +03:00

53 lines
1.4 KiB
TypeScript

export const validation = {
isValidEmail(email: string): boolean {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
},
isValidAmount(amount: string | number): boolean {
const num = typeof amount === 'string' ? parseFloat(amount) : amount;
return !isNaN(num) && num > 0;
},
isNonEmpty(value: string): boolean {
return value.trim().length > 0;
},
minLength(value: string, min: number): boolean {
return value.trim().length >= min;
},
maxLength(value: string, max: number): boolean {
return value.trim().length <= max;
},
isPositiveNumber(value: string | number): boolean {
const num = typeof value === 'string' ? parseFloat(value) : value;
return !isNaN(num) && num > 0;
},
isNonNegativeNumber(value: string | number): boolean {
const num = typeof value === 'string' ? parseFloat(value) : value;
return !isNaN(num) && num >= 0;
},
validateForm<T extends Record<string, any>>(
values: T,
rules: Partial<Record<keyof T, (value: any) => string | null>>
): Partial<Record<keyof T, string>> {
const errors: Partial<Record<keyof T, string>> = {};
for (const field in rules) {
const validator = rules[field];
if (validator) {
const error = validator(values[field]);
if (error) {
errors[field] = error;
}
}
}
return errors;
},
};