createValidationPlugin.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import type { FormKitPlugin } from '@formkit/core'
  3. import * as defaultRules from '@formkit/rules'
  4. import {
  5. createValidationPlugin as formKitCreateValidationPlugin,
  6. type FormKitValidationMessages,
  7. } from '@formkit/validation'
  8. import type {
  9. FormValidationRules,
  10. FormValidationRuleType,
  11. } from '#shared/types/form.ts'
  12. import type {
  13. ImportGlobEagerDefault,
  14. ImportGlobEagerOutput,
  15. } from '#shared/types/utils.ts'
  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. })
  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. }