All files / src/validation contactSchema.ts

100% Statements 52/52
100% Branches 7/7
100% Functions 1/1
100% Lines 52/52

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 701x 1x   1x 1x 1x                   1x 2x   2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x   2x 2x  
import { z } from 'zod'
import { toTypedSchema } from '@vee-validate/zod'
// import { stringMaxOptional } from '@/libs/vee/rules'
import { makeMsg, type TFunc } from '@/libs/vee/messages'
import { emptyToNull, nullToEmpty } from '@/utils'
import { PATTERN } from "./pattern"
 
export type ContactFields = {
  displayName: string | null;
  email: string | null;
  phone: string | null;
  notes: string | null;
  relationshipTypeId: number | null;
}
 
export function makeContactSchema(t: TFunc, L: Record<string, string>) {
  const m = makeMsg(t, L);
 
  const base = z.object({
 
    displayName: z.preprocess(
      emptyToNull,
      z
        .string()
        .trim()
        .min(1, m.req('displayName'))
        .nullable()
        .refine(v => v !== null, {
          message: m.req('displayName'),
        })
    ),
 
    email: z.preprocess(
      nullToEmpty,
      z
        .string()
        .trim()
        .nullable()
        .refine(v => !v || PATTERN.EMAIL.test(v), {
          message: m.email('email'),
        })
    ),
 
    phone: z.preprocess(
      nullToEmpty,
      z
        .string()
        .trim()
    ),
 
    relationshipTypeId: z.preprocess(
      emptyToNull,
      z
        .number()
        .int()
        .positive(m.positive('relationshipTypeId'))
        .nullable()
        .refine(v => v !== null, {
          message: m.req('relationshipTypeId')
        })
    ),
 
  }).refine(data => data.email || data.phone, {
    message: m.requiredAny(['email', 'phone']),
    path: ['email', 'phone'],
  });
 
  return toTypedSchema(base);
}