0

Could you please tell why my required check is not working in autocomplete .I am using material UI with react hook form. Step to reproduce

  • Click Submit button it show field is required.
  • then select any element from list.
  • remove the selected element Then click again submit button.It should show “required” field check.but it is not showing anything why ??

Here is my code https://codesandbox.io/s/mui-autocomplete-with-react-hook-form-0wvpq

 <Controller
      as={
        <Autocomplete
          id="country-select-demo"
          multiple
          style={{ width: 300 }}
          options={countries}
          classes={{
            option: classes.option
          }}
          autoHighlight
          getOptionLabel={option => option.label}
          renderOption={(option, { selected }) => (
            <React.Fragment>
              <Checkbox
                icon={icon}
                checkedIcon={checkedIcon}
                style={{ marginRight: 8 }}
                checked={selected}
              />
              {option.label} ({option.code}) +{option.phone}
            </React.Fragment>
          )}
          renderInput={params => (
            <TextField
              {...params}
              label="Choose a country"
              variant="outlined"
              fullWidth
              name="country"
              inputRef={register({ required: true })}
              //  required
              error={errors["country"] ? true : false}
              inputProps={{
                ...params.inputProps,
                autoComplete: "disabled" // disable autocomplete and autofill
              }}
            />
          )}
        />
      }
      onChange={([event, data]) => {
        return data;
      }}
      name="country"
      control={control}
    />
user944513
  • 12,247
  • 49
  • 168
  • 318

1 Answers1

2

When the form loads initially, the value of your form is an empty object -

{}

When you select a country (say, 'Andorra') the value of your form becomes:

{"country":[{"code":"AD","label":"Andorra","phone":"376"}]}

And then when you deselect the country, the value of your form becomes:

{"country":[]}

An empty array technically meets the "required" criteria (it's not null, after all) so your required handler doesn't fire.

You can verify this is happening by showing the value of the form in your App class -

const { control, handleSubmit, errors, register, getValues } = useForm({});
return (
  <form noValidate onSubmit={handleSubmit(data => console.log(data))}>
    <Countries control={control} errors={errors} register={register} />
    <Button variant="contained" color="primary" type="submit">
      Submit
    </Button>
    <code>{JSON.stringify(getValues())}</code>
  </form>
);

The simple fix is to NOT return an empty array as a value from your control - update your onChange handler as follows -

onChange={([event, data]) => {
    return data && data.length ? data : undefined;
}}
gerrod
  • 6,119
  • 6
  • 33
  • 45