You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

use-get-validators.ts 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import {
  2. isValidElement,
  3. useCallback,
  4. } from 'react'
  5. import type { ReactNode } from 'react'
  6. import { useTranslation } from 'react-i18next'
  7. import type { FormSchema } from '../types'
  8. import { useRenderI18nObject } from '@/hooks/use-i18n'
  9. export const useGetValidators = () => {
  10. const { t } = useTranslation()
  11. const renderI18nObject = useRenderI18nObject()
  12. const getLabel = useCallback((label: string | Record<string, string> | ReactNode) => {
  13. if (isValidElement(label))
  14. return ''
  15. if (typeof label === 'string')
  16. return label
  17. if (typeof label === 'object' && label !== null)
  18. return renderI18nObject(label as Record<string, string>)
  19. }, [])
  20. const getValidators = useCallback((formSchema: FormSchema) => {
  21. const {
  22. name,
  23. validators,
  24. required,
  25. label,
  26. } = formSchema
  27. let mergedValidators = validators
  28. const memorizedLabel = getLabel(label)
  29. if (required && !validators) {
  30. mergedValidators = {
  31. onMount: ({ value }: any) => {
  32. if (!value)
  33. return t('common.errorMsg.fieldRequired', { field: memorizedLabel || name })
  34. },
  35. onChange: ({ value }: any) => {
  36. if (!value)
  37. return t('common.errorMsg.fieldRequired', { field: memorizedLabel || name })
  38. },
  39. onBlur: ({ value }: any) => {
  40. if (!value)
  41. return t('common.errorMsg.fieldRequired', { field: memorizedLabel })
  42. },
  43. }
  44. }
  45. return mergedValidators
  46. }, [t, getLabel])
  47. return {
  48. getValidators,
  49. }
  50. }