Test freeSolo input pattern with MUI Autocomplete + React Hook Form

Viewed 14

I'm using an AutoComplete component with React Hook Form. My AutoComplete has freeSolo and multiple.

But I'm unable to test the pattern of the input in my TextField. I would like the input to follow a specific pattern and to see my field in an error state when the input doesn't match the pattern ( and more important to prevent adding the value with freeSolo in this case ). How can I reach such a result, especially without having to override onChange / onInputChange ? Here is my component:

                  <Controller
                    defaultValue={[]}
                    control={control}
                    name='versions'
                    rules={{
                      required: true,
                      pattern: { // Doesnt work...
                        value: /^[a-zA-Z0-9.-]*$/,
                        message: 'Only . - are accepted as special characters.'
                      }
                    }}
                    render={({ field: { onChange, value, ...field } }) => (
                        <Autocomplete
                          {...field}
                          freeSolo
                          multiple
                          autoSelect
                          onChange={(event, item) => {
                            onChange(item)
                          }}
                          options={[]}
                          value={value || []}
                          renderInput={(params) => (
                            <TextField
                              {...params}
                              label="Version(s)"
                              margin="normal"
                              variant="standard"
                              inputProps={{
                                ...params.inputProps,
                                required: value.length === 0,
                                pattern: /^[a-zA-Z0-9.-]*$/ // Doesnt work neither
                              }}
                              error={!!errors.versions}
                              required
                            />
                          )}
                        />
                    )}
                  />

Thanks in advance !

0 Answers
Related