Introduces field-specific validation messages so toasts name the exact field and rule that failed instead of a catch-all "tous les champs sont requis".
30 lines
907 B
TypeScript
30 lines
907 B
TypeScript
import { ArkErrors } from 'arktype'
|
|
import type { Type } from 'arktype'
|
|
import type { Composer } from 'vue-i18n'
|
|
import queueNotifService from '@/services/QueueNotifService'
|
|
|
|
type TranslateFn = Composer['t']
|
|
type MessageParams = Record<string, unknown>
|
|
export type ParamsByPath = Record<string, MessageParams>
|
|
|
|
export function validateAndNotify(
|
|
schema: Type,
|
|
data: unknown,
|
|
t: TranslateFn,
|
|
paramsByPath: ParamsByPath = {}
|
|
): boolean {
|
|
const result = schema(data)
|
|
if (!(result instanceof ArkErrors)) return true
|
|
|
|
const seen = new Set<string>()
|
|
for (const error of result) {
|
|
const pathKey = error.path.join('.')
|
|
// Skip duplicate field-level errors at the same path so the user gets one toast per field.
|
|
if (seen.has(pathKey)) continue
|
|
seen.add(pathKey)
|
|
const params = paramsByPath[pathKey] ?? {}
|
|
queueNotifService.error(t(error.message, params))
|
|
}
|
|
return false
|
|
}
|