requiredValidation.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import type { FormKitNode, FormKitProps } from '@formkit/core'
  3. const addRequired = (
  4. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5. validation: string | Array<[rule: string, ...args: any]>,
  6. ) => {
  7. if (Array.isArray(validation)) {
  8. if (!validation.includes(['required'])) validation.push(['required'])
  9. return validation
  10. }
  11. if (!validation) {
  12. return 'required'
  13. }
  14. if (!validation.includes('required')) {
  15. return `${validation}|required`
  16. }
  17. return validation
  18. }
  19. const removeRequired = (
  20. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  21. validation: string | Array<[rule: string, ...args: any]>,
  22. ) => {
  23. if (!validation) return validation
  24. if (Array.isArray(validation)) {
  25. return validation.filter(([rule]) => rule !== 'required')
  26. }
  27. if (validation.includes('required')) {
  28. return validation
  29. .split('|')
  30. .filter((rule: string) => !rule.includes('required'))
  31. .join('|')
  32. }
  33. return validation
  34. }
  35. const addRequiredToValidationProp = (props: Partial<FormKitProps>) => {
  36. const { validation } = props
  37. props.validation = addRequired(validation)
  38. }
  39. const removeRequiredFromValidationProp = (props: Partial<FormKitProps>) => {
  40. const { validation } = props
  41. props.validation = removeRequired(validation)
  42. }
  43. const addRequiredValidation = (node: FormKitNode) => {
  44. const { props, context } = node
  45. if (!props.definition || !context || node.type !== 'input') return
  46. node.addProps(['required'])
  47. if (props.required) {
  48. addRequiredToValidationProp(props)
  49. }
  50. node.hook.prop(({ prop, value }, next) => {
  51. if (prop === 'validation') {
  52. if (props.required) {
  53. value = addRequired(value)
  54. } else {
  55. value = removeRequired(value)
  56. }
  57. }
  58. return next({ prop, value })
  59. })
  60. node.on('prop:required', ({ payload }) => {
  61. if (payload) {
  62. addRequiredToValidationProp(props)
  63. } else {
  64. removeRequiredFromValidationProp(props)
  65. }
  66. })
  67. }
  68. export default addRequiredValidation