You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I don't know if it is neccassary to use conform with antd. I tried a little bit and the validation is not workin properly. Can anyone help me with this?
import{FormProviderasConformFormProvider,getFormProps,getInputProps,useFormasuseConformForm,useField,useInputControl,}from'@conform-to/react'import{getZodConstraint,parseWithZod}from'@conform-to/zod'import{useIsPending}from'@eunigos-ui/utils/misc'import{FormasAntdForm,typeFormItemPropsasAntdFormItemProps,Button,typeButtonProps,Checkbox,typeCheckboxProps,Input,typeInputProps,List,theme,}from'antd'import{typeRule}from'antd/es/form'import{typeStore}from'antd/es/form/interface'import{typePasswordProps}from'antd/es/input'importReactfrom'react'import{typez}from'zod'exporttypeListOfErrors=Array<string|null|undefined>|null|undefinedexportinterfaceErrorListProps{errors?: ListOfErrors}const{ useToken }=themeexportconstErrorList: React.FC<ErrorListProps>=({ errors })=>{const{ token }=useToken()consterrorsToRender=errors?.filter(Boolean)if(!errorsToRender?.length)returnnullreturn(<ListclassName="!p-0">{errorsToRender.map((err,i)=>(<List.ItemclassName="mb-2 !p-0"key={`${i}-${err}`}style={{color: token.colorError,}}>{err}</List.Item>))}</List>)}exportinterfaceFormProps<Schemaextendsz.ZodTypeAny>extendsOmit<React.ComponentProps<typeofAntdForm>,'form'>{formId: stringschema: SchemaconformProps?: Partial<Parameters<typeofuseConformForm>[0]>onFinish?: (values: z.infer<Schema>)=>void}exportfunctionForm<Schemaextendsz.ZodTypeAny>({
formId,
children,
conformProps,
schema,
onFinish,
...props}: FormProps<Schema>){const[form]=AntdForm.useForm()const[conformForm]=useConformForm({id: formId,constraint: getZodConstraint(schema),onValidate({ formData }){console.log('validating...',{ formData })returnparseWithZod(formData,{ schema })},onSubmit(event,context){console.log('submitting...',{ context })},shouldValidate: 'onBlur',shouldRevalidate: 'onInput',
...conformProps,})consthandleFinish=(values: z.infer<Schema>)=>{if(conformForm.valid&&onFinish){onFinish(values)}}return(<ConformFormProvidercontext={conformForm.context}><AntdFormform={form}initialValues={conformForm.initialValueasStore}onFinish={handleFinish}{...props}{...getFormProps(conformForm)}>{children}</AntdForm></ConformFormProvider>)}exportinterfaceFormItemPropsextendsOmit<AntdFormItemProps,'name'>{name: string}exportconstFormItem: React.FC<FormItemProps>=({
children,
label,
name,
rules,
validateTrigger,
validateFirst,
...props})=>{const[field,form]=useField<string>(name)constcustomRules: Rule[]=[()=>({validator(_,value){console.log({ name,fieldValue: field.value,isValid: field.valid})if(!field.valid){returnPromise.reject()}returnPromise.resolve()},message: <ErrorListerrors={field.errors}/>,}),]constnewRules: Rule[]=[...(rules??[]), ...customRules]constnewLabel=label??(name ? nameToLabel(name) : undefined)return(<AntdForm.Itemname={name}validateTrigger={validateTrigger??['onChange','onBlur']}validateFirst={validateFirst ?? 'parallel'}
validateDebounce={500}
trigger="onChange"label={newLabel}rules={newRules}{...props}>{children}</AntdForm.Item>)}/** * Submit Button */exportinterfaceSubmitButtonPropsextendsButtonProps{}exportconstSubmitButton: React.FC<React.PropsWithChildren<SubmitButtonProps>>=({ children, ...props})=>{const[submittable,setSubmittable]=React.useState(false)constform=AntdForm.useFormInstance()constisPending=useIsPending()constwatch=AntdForm.useWatch([],form)React.useEffect(()=>{form.validateFields({validateOnly: true}).then(()=>setSubmittable(true)).catch(()=>setSubmittable(false))},[form,watch])return(<Buttontype="primary"htmlType="submit"disabled={!submittable}loading={isPending}{...props}>{children}</Button>)}exportfunctionnameToLabel(name: string): string{constwords=name.split(/(?=[A-Z])|[-_]/).filter((word)=>word.length>0)constcapitalizedWords=words.map((word)=>word.charAt(0).toUpperCase()+word.slice(1).toLowerCase(),)returncapitalizedWords.join(' ')}// UtilsexporttypeRuleType=|'string'|'number'|'boolean'|'method'|'regexp'|'integer'|'float'|'object'|'enum'|'date'|'url'|'hex'|'email'exportconstRuleTypeMap: Record<string,RuleType>={text: 'string',password: 'string',email: 'email',number: 'number',checkbox: 'boolean',radio: 'enum',date: 'date',time: 'string',url: 'url',tel: 'string',color: 'string',file: 'object',range: 'number',month: 'date',week: 'string',datetime: 'date','datetime-local': 'date',}exportconstgetRules=(rules: (Rule|Record<string,any>)[]): Rule[]=>{returnrules.flatMap((rule): Rule|Rule[]=>{if(typeofrule==='object'&&'validator'inrule){returnruleasRule}else{constnewRules: Rule[]=[]if('required'inrule){newRules.push({required: rule.required,message: rule.message||`This field is required`,})}if('type'inrule){constinputType=rule.typeaskeyoftypeofRuleTypeMapnewRules.push({type:
inputTypeinRuleTypeMap
? RuleTypeMap[inputType]
: (rule.typeasRuleType),message: rule.message||`Please enter a valid ${rule.type}`,})}if('min'inrule){newRules.push({min: rule.min,message: rule.message||`Minimum value is ${rule.min}`,})}if('max'inrule){newRules.push({max: rule.max,message: rule.message||`Maximum value is ${rule.max}`,})}if('minLength'inrule){newRules.push({min: rule.minLength,message:
rule.minLengthMessage||`Minimum length is ${rule.minLength}`,})}if('maxLength'inrule){newRules.push({max: rule.maxLength,message:
rule.maxLengthMessage||`Maximum length is ${rule.maxLength}`,})}if('pattern'inrule){newRules.push({pattern: rule.pattern,message: rule.message||`Input does not match the required pattern`,})}if('whitespace'inrule){newRules.push({whitespace: rule.whitespace,message: rule.message||`This field cannot be empty`,})}returnnewRules}})}// ComponentsinterfaceBaseFieldPropsextendsFormItemProps{formElementProps?: Record<string, any>}/** * Field */exportinterfaceFieldPropsextendsBaseFieldProps{formElementProps?: InputProps}exportconstField: React.FC<FieldProps>=({
formElementProps,
rules,
...props})=>{const[field]=useField(props.name)constupdatedRules=getRules([
...(rules??[]),getInputProps(field,{type: 'text'}),])return(<FormItem{...props}rules={updatedRules}><Input{...formElementProps}/></FormItem>)}/** * Username Field */exportinterfaceUsernameFieldPropsextendsBaseFieldProps{formElementProps?: InputProps}exportconstUsernameField: React.FC<UsernameFieldProps>=({
formElementProps,
rules,
...props})=>{const[field]=useField(props.name)constupdatedRules=getRules([
...(rules??[]),getInputProps(field,{type: 'text'}),])return(<FormItem{...props}rules={updatedRules}><Input{...formElementProps}/></FormItem>)}/** * Password Field */exportinterfacePasswordFieldPropsextendsBaseFieldProps{formElementProps?: PasswordProps}exportconstPasswordField: React.FC<PasswordFieldProps>=({
formElementProps,
rules,
...props})=>{const[field]=useField<string>(props.name)constcontrol=useInputControl(field)constupdatedRules=getRules([
...(rules??[]),getInputProps(field,{type: 'password'}),])return(<FormItem{...props}rules={updatedRules}><Input.Password{...{
...formElementProps,
...getInputProps(field,{type: 'password'}),}}onChange={(e)=>control.change(e.target.value)}value={control.value}onBlur={control.blur}onFocus={control.focus}/></FormItem>)}/** * Checkbox Field */exportinterfaceCheckboxFieldPropsextendsBaseFieldProps{formElementProps?: CheckboxProps}exportconstCheckboxField: React.FC<CheckboxFieldProps>=({
formElementProps,
valuePropName,
layout,
rules,
label,
...props})=>{const[field]=useField(props.name)constupdatedRules=getRules([
...(rules??[]),getInputProps(field,{type: 'checkbox'}),])constnewLabel=nameToLabel(props.name)return(<FormItemrules={updatedRules}label=""layout={layout ?? 'horizontal'}valuePropName={valuePropName ?? 'checked'}{...props}><Checkbox{...formElementProps}>{newLabel}</Checkbox></FormItem>)}
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
I don't know if it is neccassary to use conform with antd. I tried a little bit and the validation is not workin properly. Can anyone help me with this?
Beta Was this translation helpful? Give feedback.
All reactions