| 1 | import { parseISO, isValid, isFuture, isAfter } from 'date-fns';
|
| 2 |
|
| 3 | // Email validation
|
| 4 | const isValidEmail = (email: string) => {
|
| 5 | const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
| 6 | return emailRegex.test(email);
|
| 7 | }
|
| 8 |
|
| 9 | // Password validation (minimum 6 characters)
|
| 10 | const isValidPassword = (password: string) => {
|
| 11 | return password && password.length >= 6;
|
| 12 | }
|
| 13 |
|
| 14 | // Date validation
|
| 15 | const isValidDate = (dateString: string) => {
|
| 16 | if (!dateString) return false;
|
| 17 | try {
|
| 18 | const date = parseISO(dateString);
|
| 19 | return isValid(date);
|
| 20 | } catch {
|
| 21 | return false;
|
| 22 | }
|
| 23 | }
|
| 24 |
|
| 25 | // Check if date is not in the future
|
| 26 | const isNotFutureDate = (dateString: string) => {
|
| 27 | if (!dateString) return false;
|
| 28 | try {
|
| 29 | const date = parseISO(dateString);
|
| 30 | return isValid(date) && !isFuture(date);
|
| 31 | } catch {
|
| 32 | return false;
|
| 33 | }
|
| 34 | }
|
| 35 |
|
| 36 | // Validate date range
|
| 37 | const isValidDateRange = (startDate: string, endDate: string) => {
|
| 38 | if (!startDate || !endDate) return false;
|
| 39 | try {
|
| 40 | const start = parseISO(startDate);
|
| 41 | const end = parseISO(endDate);
|
| 42 |
|
| 43 | if (!isValid(start) || !isValid(end)) {
|
| 44 | return false;
|
| 45 | }
|
| 46 |
|
| 47 | return !isAfter(start, end);
|
| 48 | } catch {
|
| 49 | return false;
|
| 50 | }
|
| 51 | }
|
| 52 |
|
| 53 | // Sanitize string input
|
| 54 | const sanitizeString = (str: string) => {
|
| 55 | if (typeof str !== 'string') return '';
|
| 56 | return str.trim().slice(0, 500); // Limit to 500 chars
|
| 57 | }
|
| 58 |
|
| 59 | // Validate required fields
|
| 60 |
|
| 61 | const validateRequiredFields = (data: Record<string, unknown>, fields: string[]) => {
|
| 62 | const missing: string[] = [];
|
| 63 |
|
| 64 | for (const field of fields) {
|
| 65 | if (data[field] === undefined || data[field] === null || data[field] === '') {
|
| 66 | missing.push(field);
|
| 67 | }
|
| 68 | }
|
| 69 |
|
| 70 | return {
|
| 71 | valid: missing.length === 0,
|
| 72 | missing
|
| 73 | };
|
| 74 | }
|
| 75 |
|
| 76 | // Validate number in range
|
| 77 | const isInRange = (value: number, min: number, max: number) => {
|
| 78 | const num = Number(value);
|
| 79 | return !isNaN(num) && num >= min && num <= max;
|
| 80 | }
|
| 81 |
|
| 82 | export {
|
| 83 | validateRequiredFields,
|
| 84 | sanitizeString,
|
| 85 | isInRange,
|
| 86 | isValidEmail,
|
| 87 | isValidPassword,
|
| 88 | isValidDateRange,
|
| 89 | isNotFutureDate,
|
| 90 | isValidDate,
|
| 91 | };
|