dify/web/app/components/base/form/hooks/use-get-validators.ts
Stephen Zhou a84c2d36a3
style: format with vp fmt (#38803)
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2026-07-12 15:57:46 +00:00

54 lines
1.7 KiB
TypeScript

import type { ReactNode } from 'react'
import type { FormSchema } from '../types'
import { isValidElement, useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { useRenderI18nObject } from '@/hooks/use-i18n'
export const useGetValidators = () => {
const { t } = useTranslation()
const renderI18nObject = useRenderI18nObject()
const getLabel = useCallback((label: string | Record<string, string> | ReactNode) => {
if (isValidElement(label)) return ''
if (typeof label === 'string') return label
if (typeof label === 'object' && label !== null)
return renderI18nObject(label as Record<string, string>)
}, [])
const getValidators = useCallback(
(formSchema: FormSchema) => {
const { name, validators, required, label } = formSchema
let mergedValidators = validators
const memorizedLabel = getLabel(label)
if (required && !validators) {
mergedValidators = {
onMount: ({ value }: any) => {
if (!value)
return t(($) => $['errorMsg.fieldRequired'], {
ns: 'common',
field: memorizedLabel || name,
})
},
onChange: ({ value }: any) => {
if (!value)
return t(($) => $['errorMsg.fieldRequired'], {
ns: 'common',
field: memorizedLabel || name,
})
},
onBlur: ({ value }: any) => {
if (!value)
return t(($) => $['errorMsg.fieldRequired'], { ns: 'common', field: memorizedLabel })
},
}
}
return mergedValidators
},
[t, getLabel],
)
return {
getValidators,
}
}