createValidationPlugin.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright (C) 2012-2023 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'
  12. import type {
  13. ImportGlobEagerDefault,
  14. ImportGlobEagerOutput,
  15. } from '@shared/types/utils'
  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. rules[validationRule.ruleType] = validationRule.rule
  24. },
  25. )
  26. return formKitCreateValidationPlugin({
  27. ...defaultRules,
  28. ...rules,
  29. })
  30. }
  31. export default createValidationPlugin
  32. export const getValidationRuleMessages = (): FormKitValidationMessages => {
  33. const ruleLocaleMessages: FormKitValidationMessages = {}
  34. Object.values(ruleModules).forEach(
  35. (module: ImportGlobEagerDefault<FormValidationRuleType>) => {
  36. const validationRule = module.default
  37. ruleLocaleMessages[validationRule.ruleType] = validationRule.localeMessage
  38. },
  39. )
  40. return ruleLocaleMessages
  41. }