Spaces:
Sleeping
Sleeping
| const mongoose = require('mongoose'); | |
| const sanitizeText = (value) => String(value ?? '').trim(); | |
| const NAME_REGEX = /^(?!.*\d)(?=.*[A-Za-z])[A-Za-z .,'-]+$/; | |
| const isValidObjectId = (id) => mongoose.Types.ObjectId.isValid(id); | |
| const parseList = (value, splitter) => { | |
| if (Array.isArray(value)) { | |
| return value.map((item) => String(item).trim()).filter(Boolean); | |
| } | |
| return String(value || '') | |
| .split(splitter) | |
| .map((item) => item.trim()) | |
| .filter(Boolean); | |
| }; | |
| const getTodayDateInput = () => { | |
| const now = new Date(); | |
| const local = new Date(now.getTime() - (now.getTimezoneOffset() * 60000)); | |
| return local.toISOString().slice(0, 10); | |
| }; | |
| const toDateInputValue = (value) => { | |
| const normalized = sanitizeText(value); | |
| if (!normalized) return ''; | |
| if (/^\d{4}-\d{2}-\d{2}$/.test(normalized)) { | |
| const [yearRaw, monthRaw, dayRaw] = normalized.split('-'); | |
| const year = Number.parseInt(yearRaw, 10); | |
| const month = Number.parseInt(monthRaw, 10); | |
| const day = Number.parseInt(dayRaw, 10); | |
| const parsed = new Date(Date.UTC(year, month - 1, day)); | |
| if (Number.isNaN(parsed.getTime())) return ''; | |
| const iso = parsed.toISOString().slice(0, 10); | |
| return iso === normalized ? normalized : ''; | |
| } | |
| const parsed = new Date(normalized); | |
| if (Number.isNaN(parsed.getTime())) return ''; | |
| const local = new Date(parsed.getTime() - (parsed.getTimezoneOffset() * 60000)); | |
| return local.toISOString().slice(0, 10); | |
| }; | |
| const isValidDateInput = (value) => { | |
| const normalized = sanitizeText(value); | |
| if (!normalized) return true; | |
| return Boolean(toDateInputValue(normalized)); | |
| }; | |
| const isFutureDateInput = (value) => { | |
| const normalized = toDateInputValue(value); | |
| if (!normalized) return false; | |
| return normalized > getTodayDateInput(); | |
| }; | |
| const isValidPersonName = (value) => { | |
| const normalized = sanitizeText(value); | |
| if (!normalized) return false; | |
| return NAME_REGEX.test(normalized); | |
| }; | |
| module.exports = { | |
| sanitizeText, | |
| isValidObjectId, | |
| parseList, | |
| isValidDateInput, | |
| isFutureDateInput, | |
| isValidPersonName, | |
| }; | |