File size: 2,083 Bytes
e8c33fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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,
};