繁体   English   中英

为 react-hook-form 实现验证消息

[英]Implement validation message for react-hook-form

我 ant 用react-hook-form实现一个表单。 我试过这个:

....
 <form onSubmit={handleSubmit(onSubmit)} className='mt-4 register-form'>
            <div className='row'>
              <div className='col-sm-6'>
                <div className='input-group mb-3'>
                  <Controller
                      control={control}
                      name={"name"} //  the key of json
                      defaultValue={""}
                      render={({ field }) => (
                          <input
                              {...field}
                              type="text"
                              className="form-control"
                              placeholder="Name"
                              aria-label="name"
                              onChange={(e) => field.onChange(e.target.value)}
                          />
                      )}
                  />
                </div>
              </div>
.....

整页代码:

https://pastebin.com/KZzsLZAn

当我提交表单时,我使用以下方式发送 POST 消息:

import axios from "axios";
import React from "react";

const baseURL = "https://jsonplaceholder.typicode.com/posts";

export const SubmitContact = (json) => {
    return axios.post(baseURL, json);
};

但是表单中没有验证消息,也没有表单成功登顶的最终消息。

你知道我如何实现这个功能吗?

尝试从useForm获取errors ,如下所示:

const { errors, ...rest } = useForm();

<div className="col-sm-6">
  <div className="input-group mb-3">
    <Controller
      control={control}
      name={"name"} //  the key of json
      defaultValue={""}
      rules={{ name: { required: true } }}
      render={({ field }) => (
        <input
          {...field}
          type="text"
          className="form-control"
          placeholder="Name"
          aria-label="name"
          onChange={(e) => field.onChange(e.target.value)}
        />
      )}
    />
    {errors.name && (
      <div className="alert alert-danger">{errors.name.message}</div>
    )}
  </div>
</div>;

要显示错误消息:

const { errors, control, handleSubmit } = useForm();

...

<form onSubmit="{handleSubmit(onSubmit)}" className="mt-4 register-form">
  <div className="row">
    <div className="col-sm-6">
      <div className="input-group mb-3">
        <Controller 
          control={control} 
          name="name"
          defaultValue="" 
          render={({ field }) => ( 
            <input 
             {...field} 
             type="text"
             className="form-control" 
             placeholder="Name" 
             aria-label="name"
             onChange={(e) => field.onChange(e.target.value)} 
            /> 
           )} 
         />
         {errors.name && <p>{errors.name.message}</p>}
      </div>
    </div>
  </div>
</form>

提交后重置表单:

const { errors, control, reset, handleSubmit } = useForm();

...

const onSubmit = (formData) => {
    try {
      SubmitContact(formData).then((res) => {
        setPost(res.data);
        reset();
      });
    } catch (e) {
      console.error(e);
    }
};

您在Controller组件中没有正确使用rules ,您不需要定义注册输入的名称,您只需说出规则:

rules={{ 
   required: "Required", // Note you are wrapping this inside a key which is not required
}}

要访问此错误消息,您需要使用formState中的useForm

const {formState: {errors}} = useForm()

// accessing errors
{errors.country?.message}

为了清除表格只需使用reset

这是您的代码的工作沙箱: https://codesandbox.io/s/late-haze-jivrwp?file=/src/App.js

提交时,您可以看到国家/地区字段上弹出错误

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM