3

Having a not mandatory numeric input like the following one:

import { useForm } from 'react-hook-form';

export default function App() {
  const { register, handleSubmit, formState: { errors } } = useForm();
  const onSubmit = data => console.log(data);
  console.log(errors);
  
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input type="number" placeholder="Age" name="Age" ref={register({maxLength: 80}) />

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

I would expect to get a number or null on submit. However I get an string:

{
  "Age": ""
}

Or

{
  "Age": "10"
}

I could customize the register function as mentioned here to convert it to a number, however I would like to have this behavior by default. This way I wouldn't have to remember to include the function on each input.

I tried to extend useForm but I didn't succeed. Is there a way to, by default, getting number or null values from numeric inputs?

5
  • 1
    Is using a schema validation (for example yup) an option for you? Commented Mar 6, 2022 at 8:18
  • Thanks for your suggestion, it's a better approach than using register function on each input. However it still forces me to remember to include yup on each form. What I'm looking for is a way to configure useForm or extends from it, to whenever I call useForm, by default I get numbers or null for numeric inputs. Anyway, if I don't find any other way your suggestions it's the better approach I guess Commented Mar 6, 2022 at 8:42
  • After checking your suggestion I realized it doesn't works to me, yup is for validation and what I actually need is getting a certain value by default instead of validating Commented Mar 8, 2022 at 7:59
  • yup can also be used to transform values. Commented Mar 8, 2022 at 8:54
  • Check this out also Commented Mar 8, 2022 at 8:58

1 Answer 1

2

There's two ways about this: One would be to include the default value in the initial form values. You can do that by const form = useForm({ defaultValues: { "Age": null }}); or by using the options of the register function provided by useForm.

<input type="number" placeholder="Age" name="Age" ref={register({maxLength: 80, setValueAs: (v) => v === "" ? null : parseInt(v)}) /> read more about how these work in the official docs: https://react-hook-form.com/api/useform/register/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.