Ant 设计复选框反应钩形式验证

时间:2021-01-22 10:08:58

标签: reactjs validation antd yup react-hook-form

这是我的 jsx:

            <Form.Item
              name="agreement"
              validateStatus={errors.agreement ? 'error' : 'success'}
              help={errors.agreement?.message}
              valuePropName="checked"
            >
              <Controller
                name="agreement"
                control={control}
                render={(props) => (
                  <Checkbox {...props}>
                    من
                    <a href="" onClick={showModal}>
                      {' '}
                      قوانین و شرایط{' '}
                    </a>
                    را می پذیرم
                  </Checkbox>
                )}
              />
            </Form.Item>

这是我的反应钩子形式:

  const { handleSubmit, control, errors, getValues, reset } = useForm({
    mode: 'onChange',
    defaultValues: {
      agreement: true,
    },
    resolver: yupResolver(registerValidationSchema),
  })

这是是的验证架构:

const registerValidationSchema =  Yup.object().shape({
  agreement: Yup.boolean().oneOf([true], 'لطفا قوانین و شرایط را بپذیرید.'),
})

最后这是我无法解决的错误消息。

警告:[antd: Checkbox] value 不是有效道具,您是说 checked 吗?

2 个答案:

答案 0 :(得分:0)

antd Checkbox 接受 checked 作为值而不是 truefalse。试试这个:

const { handleSubmit, control, errors, getValues, reset } = useForm({
    mode: 'onChange',
    defaultValues: {
      //agreement: true,
        agreement: "checked"
    },
    resolver: yupResolver(registerValidationSchema),
})

答案 1 :(得分:0)

 <Form.Item
              name="agreement"
              validateStatus={errors.agreement ? 'error' : 'success'}
              help={errors.agreement?.message}
              valuePropName="checked"
            >
              <Controller
                name="agreement"
                control={control}
                render={({ value, ...restProps }) => (
                  <Checkbox
                    {...restProps}
                    onChange={(e) =>
                      setValue('agreement', e.target.checked, {
                        shouldValidate: true,
                        shouldDirty: true,
                      })
                    }
                    checked={value}
                  >
                    من
                    <a href="" onClick={showModal}>
                      {' '}
                      قوانین و شرایط{' '}
                    </a>
                    را می پذیرم
                  </Checkbox>
                )}
              />
            </Form.Item>

完成