简体   繁体   中英

Using Rules on React-Hook-Form

Overview

I am using React-Hook-Form to manage validation on my input fields. I am leveraging react bootstrap so I have to make use of the Controller component provided with this library.

Documentation is not clear about how to use rules; just that its that same as register . I am able to get one validation rule working (required). For dropdowns, I always have at least one value selected ("select"), so required does not work, instead I am trying to use regex to see if the selection is this or not.

I have tried many ways to get this work but unfortunately I can't figure this out.

Question

Does any have experience in using React-Hook-Form with Controlled components, specifically dropdowns and regex? I am looking for the syntax on how what they define in register within the rules of the controller component. Only required seems to work

Here is what works (notice the rules prop)

<TextInputField
            label="Operation Info"
            name="operation_info"
            control={control}
            rules={{ required: "Operation is required" }}
            error={errors?.name}
          />

This does not work (notice the rules prop)

I am trying this on another custom component except it a dropdown.

<Dropdown
            label="Ratings"
            name="ratings"
            control={control}
            rules={{ pattern: /^(?!select$).*/ }}
            options={ratings}
            optionsKey={"rating"}
            error={errors?.indicator}
          />

I tried a copy paste of their actual pattern rule but this also does not work. I am able to hook into all errors in my forms but anything using pattern does not register as an error.

This second one does not work. I spread these props on the actual react-bootstrap components in another file. They are all the same, so the fact the text-input works, means the dropdown should work as well but it does not. Only difference I see it the rules I am applying; I must be doing it wrong but there is no documentation.

Here is a sample of the dropdown component:

import React from "react";
import { Form } from "react-bootstrap";
import { Controller } from "react-hook-form";

export const Dropdown = (props) => {
  const { error, name, control, label, rules, options, optionsKey } = props;
  return (
    <Form.Group>
      <Form.Label>{label}</Form.Label>
      <Controller
        name={name}
        control={control}
        rules={rules}
        render={({ field }) => (
          <Form.Control
            {...field}
            as="select"
            className={error ? `is-invalid` : null}
          >
            <option selected disabled className="text-muted" value="select">
              select
            </option>
            {options?.length > 0
              ? options.map((option, index) => {
                  return (
                    <option value={option[optionsKey]} key={index}>
                      {option[optionsKey]}
                    </option>
                  );
                })
              : null}
          </Form.Control>
        )}
      />
      <Form.Control.Feedback type="invalid">
        {error?.message}
      </Form.Control.Feedback>
    </Form.Group>
  );
};
export default Dropdown;

here is the link to the controller documentation https://react-hook-form.com/api/usecontroller/controller

I did a minimized test setup and if I understood your question to me it looks like the problem is just with your regex. Try

rules={{ required: "req", pattern: /^(?!select)/ }}

Click here for test sandbox and iIn case the sandbox goes away:

import * as React from "react"
import { useForm, Controller } from "react-hook-form"

const Dropdown = ({ name, control, rules, options }) => {
  return (
    <Controller
      name={name}
      control={control}
      rules={rules}
      render={({ field }) => (
        <select {...field} rules={rules}>
          <option value="select">select</option>
          <option value=""></option>
          {options.map(x => <option key={x} value={x}>{x}</option>)}
        </select>
      )}
    />
  )
}

export default function App() {
  const { handleSubmit, control, formState: {errors} } = useForm()
  const onSubmit = (data) => console.log("Submit:", data)

  console.log("Errors:", errors?.ratings)

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Dropdown
        name="ratings"
        control={control}
        rules={{ required: "Requir", pattern: /^(?!select)/ }}
        options={["potato", "tomato", "select", "greg"]}
      />
      <input type="submit" />
      {errors && errors.ratings && <p>
        Error: {errors.ratings.type} {errors.ratings.message}</p>
      }
    </form>
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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