Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

use-check-validated.ts 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { useCallback } from 'react'
  2. import type { AnyFormApi } from '@tanstack/react-form'
  3. import { useToastContext } from '@/app/components/base/toast'
  4. import type { FormSchema } from '@/app/components/base/form/types'
  5. export const useCheckValidated = (form: AnyFormApi, FormSchemas: FormSchema[]) => {
  6. const { notify } = useToastContext()
  7. const checkValidated = useCallback(() => {
  8. const allError = form?.getAllErrors()
  9. const values = form.state.values
  10. if (allError) {
  11. const fields = allError.fields
  12. const errorArray = Object.keys(fields).reduce((acc: string[], key: string) => {
  13. const currentSchema = FormSchemas.find(schema => schema.name === key)
  14. const { show_on = [] } = currentSchema || {}
  15. const showOnValues = show_on.reduce((acc, condition) => {
  16. acc[condition.variable] = values[condition.variable]
  17. return acc
  18. }, {} as Record<string, any>)
  19. const show = show_on?.every((condition) => {
  20. const conditionValue = showOnValues[condition.variable]
  21. return conditionValue === condition.value
  22. })
  23. const errors: any[] = show ? fields[key].errors : []
  24. return [...acc, ...errors]
  25. }, [] as string[])
  26. if (errorArray.length) {
  27. notify({
  28. type: 'error',
  29. message: errorArray[0],
  30. })
  31. return false
  32. }
  33. return true
  34. }
  35. return true
  36. }, [form, notify, FormSchemas])
  37. return {
  38. checkValidated,
  39. }
  40. }