Susana.96
Susana.96

Reputation: 61

Material-UI Autocomplete: how to set as a required field

I'm building a form using Material UI autocomplete (multiple). I need that field to be required. But when i submit the form, with selected value, it allways show the message that the field is required. This problem only occurs if the option multiple = true.

Anyone knows how to solve the problem?

Sample of code in sandbox

Upvotes: 6

Views: 11712

Answers (2)

New
New

Reputation: 1

             <Controller
                name="jobTitle"
                control={control}
                render={({ field: { onChange, value }, fieldState: { error } }) 
                  => (
                  <Autocomplete
                    disableClearable
                    onChange={(event, item) => onChange(item)}
                    value={value}
                    options={jobTitles.map((jt) => jt)}
                    getOptionLabel={(jt) => jt}
                    renderOption={(props, jt) => (
                      <Box component="li" {...props} key={jt}>
                        {jt}
                      </Box>
                    )}
                    renderInput={(params) => (
                      <TextField
                        label={translate('pages.profile.job_title')}
                        {...params}
                        error={!!error}
                        helperText={error ? 'Job Title is required' : ''}
                      />
                    )}
                  />
                )}
              />

Upvotes: 0

Chris
Chris

Reputation: 348

Try checking that if the length of the input value array is 0 in the input props of the textfield.

<Autocomplete
      includeInputInList={false}
      options={options}
      getOptionLabel={(option) => option.name}
      onChange={(event, newValue) => {
        setValue(newValue);
      }}
      value={value}
      renderInput={(params) => (
        <TextField
          {...params}
          variant="standard"
          label={"Names"}
          inputProps={{
            ...params.inputProps,
            autoComplete: "new-password",
            required: value.length === 0
          }}
          required={true}
        />
      )}

sample in codesandbox

Upvotes: 9

Related Questions