createValidationPlugin.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import * as defaultRules from '@formkit/rules'
  3. import {
  4. createValidationPlugin as formKitCreateValidationPlugin,
  5. type FormKitValidationMessages,
  6. } from '@formkit/validation'
  7. import type {
  8. FormValidationRules,
  9. FormValidationRuleType,
  10. } from '#shared/types/form.ts'
  11. import type {
  12. ImportGlobEagerDefault,
  13. ImportGlobEagerOutput,
  14. } from '#shared/types/utils.ts'
  15. import type { FormKitPlugin } from '@formkit/core'
  16. const ruleModules: ImportGlobEagerOutput<FormValidationRuleType> =
  17. import.meta.glob('../validation/rules/*.ts', { eager: true })
  18. const createValidationPlugin = (): FormKitPlugin => {
  19. const rules: FormValidationRules = {}
  20. Object.values(ruleModules).forEach(
  21. (module: ImportGlobEagerDefault<FormValidationRuleType>) => {
  22. const validationRule = module.default
  23. if (!validationRule?.ruleType) return
  24. rules[validationRule.ruleType] = validationRule.rule
  25. },
  26. )
  27. return formKitCreateValidationPlugin({
  28. ...defaultRules,
  29. ...rules,
  30. } as unknown as FormValidationRules)
  31. }
  32. export default createValidationPlugin
  33. export const getValidationRuleMessages = (): FormKitValidationMessages => {
  34. const ruleLocaleMessages: FormKitValidationMessages = {}
  35. Object.values(ruleModules).forEach(
  36. (module: ImportGlobEagerDefault<FormValidationRuleType>) => {
  37. const validationRule = module.default
  38. if (!validationRule?.ruleType) return
  39. ruleLocaleMessages[validationRule.ruleType] = validationRule.localeMessage
  40. },
  41. )
  42. return ruleLocaleMessages
  43. }