Home > Back-end >  react-hook-form check if a value is included in an array
react-hook-form check if a value is included in an array

Time:01-25

I'm working with react-hook-form, and I have the following code

const array = ['foo', 'bar']

const Form = () => {
  const { handleSubmit, register } = useForm();

  return (
    <div>
      <form onSubmit={handleSubmit(submitFunction)}>
        <input
          type="text"
          {...register("value", {
            required: true,
          })}
        />

        <input type="submit" />
      </form>
    </div>
  );
};

Is there a way to check if a registered input value is included in the array? Something like

array.includes(value)

Thanks in advance

CodePudding user response:

From offical doc:

You can pass a callback function as the argument to validate, or you can pass an object of callback functions to validate all of them. This function will be executed on its own without depending on other validation rules included in the required attribute. Note: for object or array input data, it's recommended to use the validate function for validation as the other rules mos tly apply to string, string[], number and boolean data types.

<input
  {...register("test", {
    validate: value => value === '1' || 'error message'  // JS only: <p>error message</p> TS only support string
  })}
/>

For the error message


    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("singleErrorInput", { required: "This is required." })} />
      <ErrorMessage errors={errors} name="singleErrorInput" />
      
      <ErrorMessage
        errors={errors}
        name="singleErrorInput"
        render={({ message }) => <p>{message}</p>}
      />
      
      <input type="submit" />
    </form>

you can pass callback funcation in validate

  • Related