标签: react-hook-form

反应中采取错误验证的多步骤形式

我在这里写我的问题作为一个新的部分。

我制作了一个多步骤表单,其中我在第一个表单中进行了动态归档,该字段是手动创建密码或仅自动生成密码。

所以我的多步表单工作正常,来回正常,但我必须将字段传递给主要组件,以便它可以检查验证,并且我也在传递该密码

问题来了

当我通过该password字段时,即使我点击了自动生成的密码,它也会进行验证

我正在通过这样的领域 fields: ["uname", "email", "password"], //to support multiple fields form

所以即使不检查让我创建密码也需要验证。

当我点击让我创建密码并输入一些值然后点击下一步时,当我回来时,输入字段再次设置为隐藏到其初始状态我知道为什么会发生这种情况,因为当我回来时,它会再次恢复初始状态.

我现在厌倦了这件事,我已经尝试了很多事情,但没有奏效,下面是我的代码

    import React, { useState, useEffect } from "react";
import Form1 from "./components/Form1";
import Form2 from "./components/Form2";
import Form3 from "./components/Form3";
import { useForm } from "react-hook-form";

    function MainComponent() {
      const { register, triggerValidation, errors, getValues } = useForm();
      const [defaultValues, setDefaultValues] = useState({});
    
      const forms = [
        {
          fields: ["uname", "email", "password"], //to support multiple fields form
          component: (register, errors, …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-hooks react-hook-form

7
推荐指数
1
解决办法
642
查看次数

“isValid”始终为假

我使用自定义registerreact-hook-form,我无法得到formState.isValidtrue,当我输入文本输入(所以满足required条件)。

这是一个示例代码:

interface FormValues {
  readonly value: string;
}

export default function App() {
  console.log("rendering");

  const form: UseFormMethods<FormValues> = useForm<FormValues>({
    mode: "onChange",
    reValidateMode: "onChange",
    defaultValues: { value: "" }
  });

  useEffect(() => {
    form.register({ name: "value" }, { required: true });
  }, [form, form.register]);

  const { isValid } = form.formState;
  const value = form.watch("value");

  return (
    <div>
      <input
        onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
          form.setValue("value", e.target.value);
        }}
      />
      <div>IsValid: {JSON.stringify(isValid)}</div>
      <div>Errors: {JSON.stringify(form.errors)}</div> …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hook-form

7
推荐指数
2
解决办法
4399
查看次数

如何使用 React-Hook-Form 设置 ref 焦点

您如何使用 React-Hook-Form 在输入中实现设置焦点,这是他们的常见问题解答中的“如何共享引用使用”代码https://www.react-hook-form.com/faqs/#Howtosharerefusage

import React, { useRef } from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const { register, handleSubmit } = useForm();
  const firstNameRef = useRef();
  const onSubmit = data => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="firstName" ref={(e) => {
        register(e)
        firstNameRef.current = e // you can still assign to ref
      }} />
      <input name="lastName" ref={(e) => {
        // register's first argument is ref, and second is validation rules
        register(e, { required: …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hook-form

7
推荐指数
3
解决办法
8626
查看次数

使用反应钩子形式进行条件验证

这是我的表单和CodeSanbox 的样子。目前我正在使用 react-hook-form,
因为您可以看到表单有 3 个输入。在输入所有必填字段之前,应禁用提交按钮。两个用例:

  1. 如果未选中“检查”:
    • 只有“id”应该被验证并且提交按钮应该被启用。“第一个”和“姓氏”名称不应是表单数据的一部分
  2. 如果选中“检查”
    • 所有字段都应验证
      名字,只有在选中“检查”时才需要姓氏。所以它没有被检查然后表单应该只验证“ID”字段。如果选中“检查”,则所有字段都应得到验证。

我遇到的问题是,如果我输入 id,表单状态仍然是“无效”。表单需要输入名字和姓氏的值。
我将不胜感激任何帮助。

形式

reactjs react-hooks react-hook-form react-forms

7
推荐指数
2
解决办法
1万
查看次数

React-Hook-Form:输入空白时如何不显示错误

一旦触摸了某个组件,然后用户清除了输入,默认行为是继续显示错误。如何才能使触摸后清除输入时错误消失?

下面的代码是文档的摘录

import React from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const { register, formState: { errors }, handleSubmit } = useForm();
  
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("firstName", { required: true })} />
      {errors.firstName?.type === 'required' && "First name is required"}
      
      <input {...register("lastName", { required: true })} />
      {errors.lastName && "Last name is required"}
      
      <input type="submit" />
    </form>
  );
}

Run Code Online (Sandbox Code Playgroud)

reactjs react-hook-form

7
推荐指数
1
解决办法
9389
查看次数

使用react-hook-form进行react-phone-number-input验证

phone-number-input]( https://gitlab.com/catamphetamine/react-phone-number-input#readme ) 与react-hook-form一起工作正常。我想使用react-phone-number-input中的isValidPhoneNumber验证电话号码,但我不知道如何使用react-hook-form来实现这一点。我在这里读过一些关于这个问题的帖子,但对我来说没有正确的答案。这是我的代码:

import { useForm, Controller } from 'react-hook-form'
import PhoneInput, { isValidPhoneNumber } from 'react-phone-number-input'

import 'react-phone-number-input/style.css'

const MyForm = () => {
  const {
    handleSubmit,
    formState: { errors },
    control,
  } = useForm()

  const onSubmit = (data) => {
    console.log(data)
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="user-info-form">
      <div>
        <label htmlFor="phone-input">Phone Number</label>
        <Controller
          name="phone-input"
          control={control}
          rules={{ required: true }}
          render={({ field: { onChange, value } }) => (
            <PhoneInput
              value={value}
              onChange={onChange}
              defaultCountry="TH"
              id="phone-input"
            />
          )}
        /> …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hook-form

7
推荐指数
1
解决办法
3万
查看次数

是的,对选择字段(下拉列表)的验证反应钩子形式不起作用

我是ReactJs中的新手,所以我正在使用react-hook-form和Yup模式验证,我需要验证我的“选择字段”,并且当我的“选择字段”onChange时我需要做一些事情。但模式验证不起作用。例如:当单击提交按钮并且“选择字段”上的值为空/空时,会出现错误消息,但是当选择字段值更改为非空/非空值时,错误消息不会消失,并且错误消息仍然退出。我的目标是当“选择字段”值不为空时,错误消息消失。有人知道怎么修这个东西吗?预先感谢并为我蹩脚的英语感到抱歉。下面是我的代码和codesandbox 中的链接。 代码沙箱

import React from "react";
import ReactDOM from "react-dom";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";

import "./styles.css";

const SignupSchema = yup.object().shape({
  select: yup.string().required()
});

function App() {
  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm({
    mode: "onChange",
    resolver: yupResolver(SignupSchema)
  });
  const onSubmit = (data) => {
    alert(JSON.stringify(data));
  };

  const doSomething = (value) => {
    // do something with my select value onChange
  }; …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs yup react-hooks react-hook-form

7
推荐指数
1
解决办法
3万
查看次数

粘贴值后反应钩子表单验证不起作用

我为表单创建了一个模型,该模型通过它进行映射以使用react-hook-form创建表单

当我第一次提交表格时,一切都很好。但在其他时候,当我将值粘贴到输入中时,验证无法正常工作(它显示所需的错误,但输入不为空)

这是模型:

export const formData = [
  {
    id: 1,
    type: "text",
    labelRequired: true,
    label: "name",
    shape: "inline",
    placeholder: "name",
    name: "nameOne",
    validation: {
      required: true,
      minLength: 8,
    },
    size: 6,
  },
  {
    id: 2,
    type: "text",
    labelRequired: true,
    label: "family",
    shape: "inline",
    placeholder: "family",
    name: "nameTwo",
    validation: {
      required: true,
      minLength: 8,
    },
    size: 6,
  },
  {
    id: 7,
    type: "checkbox",
    label: "Sample",
    shape: "checkbox",
    placeholder: "placeholder",
    name: "checkbox_btn",
    data: [
      {
        id: 41,
        inputId: "inline-form-1",
        label: "1", …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hooks react-hook-form

7
推荐指数
1
解决办法
1554
查看次数

TypeError:e.preventDefault 不是使用 EmailJs 的 React Hook Form 上的函数

提交表单后出现错误:
TypeError: e.preventDefault is not a function。

这是我的代码:

import {React} from 'react';
import emailjs from 'emailjs-com';
import {useForm} from "react-hook-form";

const NameForm = () => {
  const { register, handleSubmit, formState: { errors } } = useForm();
  const sendEmail = (e) => {
    e.preventDefault();

    emailjs.sendForm('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', e.target, 'YOUR_USER_ID')
      .then((result) => {
          console.log(result.text);

      }, (error) => {
          console.log(error.text);
      });
      e.target.reset();
  }

    return (
      <div>
        <h1 className="text-center text-md-left mb-3">Get in Touch</h1>
        <form className="contact-form" onSubmit={handleSubmit(sendEmail)}>
          <div className="form-group mb-0 py-3">
            <textarea className="form-control custom--fields-mod text-the-primary" …
Run Code Online (Sandbox Code Playgroud)

javascript email reactjs react-hook-form

7
推荐指数
1
解决办法
2万
查看次数

如何通过在react中使用react-hook-form来获取react-phone-input-2值

我在提交时获取 TextField 值,但不是 ReactPhoneInput 值,如何使用react-hook-form获取该值

import ReactPhoneInput from "react-phone-input-2"
import {TextField,Button}from "@material-ui/core"

const {register, handleSubmit,formState: { errors }} = useForm()

const getData= (data) => {
   console.log(data.username)
   console.log(data.username);
}

Run Code Online (Sandbox Code Playgroud)

形式

<form onSubmit={handleSubmit(getData)} >

  <TextField {...register("username")} />

   <ReactPhoneInput
      inputExtraProps={{
        name: "phone",
        required: true,
        autoFocus: true
      }}

      country={"in"}
       onlyCountries={["in"]}                     
       countryCodeEditable={false}
        specialLabel={"Player Mobile Number"}
       rules={{ required: true }}
     />
<Button type='submit>Submit</Button> 
</form>
Run Code Online (Sandbox Code Playgroud)

reactjs react-hook-form

6
推荐指数
1
解决办法
5829
查看次数