react-hook-form icon indicating copy to clipboard operation
react-hook-form copied to clipboard

Custom Input validation

Open alleyshairu opened this issue 7 years ago • 34 comments

Hello, I can't seem to figure out why the validation doesn't work on custom inputs like Select2.

I have created a fork of your custom input example, which already registers the select input, so I just added the required validation, now I expect that the reactSelect value will be available when the onSubmit function is triggered, but it's missing from data.

Screenshot_2019-05-24_11-55-42

My understanding is that required validation will make sure all inputs values are available when the onSubmit function is triggered. Maybe I am wrong? I also can't seem to make other validation rules work for custom input.

How would you go about solving this? setError maybe?

and Thank you for creating this.

alleyshairu avatar May 24 '19 07:05 alleyshairu

Hey @AlleyShairu,

Is this what you after?

Screen Shot 2019-05-24 at 6 06 46 pm

for a required field, you need to do register({ required: true })

let me know if this makes sense?

cheers bill

bluebill1049 avatar May 24 '19 08:05 bluebill1049

looks like react-select return empty array when nothing is selected, I may need to patch to fix required validation. will keep you updated.

bluebill1049 avatar May 24 '19 09:05 bluebill1049

@bluebill1049 Take the below component as an example mentioned in the codepen

<Select
  className="reactSelect"
  name="filters"
  placeholder="Filters"
  value={values.selectedOption}
  options={options}
  onChange={handleMultiChange}
  ref={e => register({ name: "reactSelect", required: true })}
/>

I have added the register({ name: "reactSelect", required: true })

Now what would happen if I submit the form without interacting with this input?

  • If it's submitting the form I should see the reactSelect value in the data object, even if it's the empty array.
  • Or it shouldn't let me submit the form and populates the error object.

This is what I am getting after clicking the submit button without interacting with the input.

Screenshot_2019-05-24_14-45-08

I am getting the same behavior with other components like react datepicker.

Thanks for spending your time on this.

alleyshairu avatar May 24 '19 10:05 alleyshairu

Thanks for the issue report, I will sort out ASAP.

bluebill1049 avatar May 24 '19 10:05 bluebill1049

https://codesandbox.io/s/react-hook-form-custom-input-dyh9q

try this one, let me know if make sense.

https://github.com/bluebill1049/react-hook-form/releases/tag/v3.7.3

bluebill1049 avatar May 24 '19 12:05 bluebill1049

It does, tested with react-datepicker too.

So now to make the validation work on custom input, we should use the second parameter for rules like (required or validate) in register function.

Thanks a lot for your hard work.

alleyshairu avatar May 24 '19 13:05 alleyshairu

yea :) that's correct. I used to validate with react select because return value can be an empty array. If you find the package useful please kindly leave a star to support, much appreciated. ❤️

bluebill1049 avatar May 24 '19 14:05 bluebill1049

@alleyshairu could you share that example with the react-date-picker?? that would be awesome

ethaneisenhard avatar Dec 10 '19 22:12 ethaneisenhard

@ethaneisenhard https://codesandbox.io/s/stoic-kirch-6oq7p I just created this for you.

Basically, maintain the state of your custom input like you usually do, but also register the input so that the react-form-hook can know about it. You usually do it like

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

and then whenever the input value change you use the react-form-hook setValue to assign the value to the input you registered. Now, this value will be available onSubmit.

<DatePicker
	isClearable
	selected={date}
	onChange={val => {
	setDate(val);
	setValue("date", val); // Here we are setting the value for the registered input.
	}}
/> 

Hope this was helpful.

alleyshairu avatar Dec 12 '19 02:12 alleyshairu

thanks a lot @alleyshairu for sharing with us!

bluebill1049 avatar Dec 12 '19 03:12 bluebill1049

For some reason when doing the custom register with <FormContext /> the methods.handleSubmit does not fire.

The parent component which contains the form

const Page: React.FunctionComponent = () => {
  const onSubmit = () => {
    console.log("clicked");
    methods.handleSubmit(data => {
      console.log("data", data); // <-- this does not log
    });
  };

  return (
    <FormContext {...methods}>
      <form className="w-full">
        <FormSectionWithDate></FormSectionWithDate>
        <div className="py-6">
          <button onClick={onSubmit}>Save</button>
        </div>
      </form>
    </FormContext>
  );
};

The date component with the custom register

const DatePicker: React.FunctionComponent = () => {
  const [startDate, setStartDate] = useState<any>(new Date());
  useEffect(() => {
    register({ name: "date" }, { required: true });
  }, []);

  return (
    <DatePicker
      onChange={val => {
        setStartDate(val);
        setValue(name, val);
        console.log(val);
      }}
      value={startDate}
    />
  );
};

This is the the date picker library I'm using is wojtekmaj/react-date-picker

iamdevlinph avatar Dec 21 '19 15:12 iamdevlinph

Also tried with [register] but still no luck

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

iamdevlinph avatar Dec 21 '19 15:12 iamdevlinph

@iamdevlinph can you share a codesandbox for this and which version of RHF are you using?

bluebill1049 avatar Dec 21 '19 21:12 bluebill1049

I'm trying to create one but I always get a cross-origin error when I add the following code.

<form onSubmit={methods.handleSubmit(onSubmit)}>

I might just create a repository for it

iamdevlinph avatar Dec 22 '19 04:12 iamdevlinph

I just realized the issue.

I was doing the wrong object for register

useEffect(() => {
    register({ name }, { required });
}, []);

instead of

useEffect(() => {
    register({ name, required });
}, []);

🤦‍♂️🤦‍♂️

iamdevlinph avatar Dec 22 '19 06:12 iamdevlinph

@iamdevlinph all good. show me the error that you got if you have sometime too :)

bluebill1049 avatar Dec 22 '19 06:12 bluebill1049

I see. I understood my issue now.

With this syntax

useEffect(() => {
    register({ name, required });
}, []);

the required is treated as a form field that's why the methods.handleSubmit triggers even though there are empty required fields.

While in this syntax (which is correct)

useEffect(() => {
    register({ name}, {required});
}, []);

the required is the actual required option and that's why when I submit the form it doesn't trigger anything because there are empty required fields.


This is just a user error so I'm not sure if this can be prevented in the library. Maybe add a warning or prompt when a required is detected in the Element obj like,

"It seems you are using 'required' as an input name or something"

iamdevlinph avatar Dec 22 '19 07:12 iamdevlinph

all good @iamdevlinph thanks for let us know too 👍

next major version, we are simplify the API a bit. hopefully make your guys' life easier too.

bluebill1049 avatar Dec 22 '19 07:12 bluebill1049

It's quite simple enough. Just some bad eyesight 😅

iamdevlinph avatar Dec 22 '19 07:12 iamdevlinph

@iamdevlinph if you find it useful in the future, Please consider leave us a star too 🙏

bluebill1049 avatar Dec 22 '19 07:12 bluebill1049