useFileValidation.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { createMessage, type FormKitNode } from '@formkit/core'
  3. import { i18n } from '#shared/i18n.ts'
  4. import {
  5. type AllowedFile,
  6. humanizeFileSize,
  7. validateFileSizes,
  8. } from '#shared/utils/files.ts'
  9. export const useFileValidation = () => {
  10. const validateFileSize = (
  11. node: FormKitNode,
  12. files: FileList | Array<File>,
  13. allowedFiles: AllowedFile[],
  14. options = {
  15. writeToMsgStore: false,
  16. },
  17. ) => {
  18. const fileList = Array.isArray(files) ? files : Array.from(files)
  19. const failedFiles = validateFileSizes(fileList, allowedFiles)
  20. if (failedFiles.length === 0) return true
  21. const failedFile = failedFiles[0]
  22. const errorMsg = i18n.t(
  23. 'File is too big. %s has to be %s or smaller.',
  24. failedFile.label,
  25. humanizeFileSize(failedFile.maxSize),
  26. )
  27. if (options.writeToMsgStore) {
  28. node.store.set(
  29. createMessage({
  30. key: 'fileSizeError',
  31. blocking: true,
  32. value: errorMsg,
  33. type: 'validation',
  34. visible: true,
  35. }),
  36. )
  37. } else {
  38. node.setErrors(errorMsg)
  39. }
  40. return false
  41. }
  42. return { validateFileSize }
  43. }