如何使材料 UI 的自动完成字段需要?

Pus*_*dav 6 reactjs material-ui react-hook-form

我尝试了几种方法来使材料 UI 的自动完成类型字段成为必需,但我没有得到我想要的行为。我已经将我的领域封装在 react hook 形式中,<Controller/>但没有运气。当没有向字段添加任何内容时,我想在提交时触发消息“字段是必需的”。

下面是代码片段,我没有删除注释,以便其他人更容易理解我之前遵循的方法 -

  <Controller
        name="displayName"
        as={
          <Autocomplete 
                  value={lists}
                  multiple
                  fullWidth
                  size="small"
                  limitTags={1}
                  id="multiple-limit-lists"
                  options={moduleList}
                  getOptionLabel={(option) => option.displayName}
                  renderInput={(params,props) => {
                   return (
                      <div>
                        <div className="container">
                          <TextValidator {...params} variant="outlined" label="Display Name*" className="Display Text" 
                            name="displayName"  id="outlined-multiline-static" 
                            placeholder="Enter Display-Name" size="small"
        onChange={handleDisplay}
         // validators={['required']} this and below line does throw a validation but the problem is this validation stays on the screen when user selects something in the autocomplete field which is wrong.
        // errorMessages={['This field is required']} 
        // withRequiredValidator
        
                            />
                        </div>
                      </div>
                    )
                  }}
                  />
        }
        // onChange={handleDisplay}
        control={control}
        rules={{ required: true }}
        // required
        // defaultValue={options[0]}
        />
        <ErrorMessage errors={errors} name="displayName" message="This is required" />

Run Code Online (Sandbox Code Playgroud)

Nik*_*kos 14

您可以使用以下逻辑来使其工作。虽然这可能不是最好的解决方案,但确实有效。

<Autocomplete 
    renderInput={(params) => (
        <TextField
            {...params}
            label={value.length === 0 ? title : title + " *"} //handle required mark(*) on label 
            required={value.length === 0}
        />
    )}
/>
Run Code Online (Sandbox Code Playgroud)


小智 8

我尝试使用文本字段中内置的必需内容进行自动完成,它的工作方式就像一个魅力。也许你可以用这个作为参考。

<Autocomplete
    renderInput={(params) => {
        <TextField {...params} required />
    }
    // Other codes
/>
Run Code Online (Sandbox Code Playgroud)

  • 问题是 MUI 自动完成的“多个”选项与“必需”属性不能很好地配合。启用“多个”后,自动完成会将值存储在数组中,但支持该控件的 HTML 输入元素将具有字符串值“”,因此无法通过“required”属性验证。 (3认同)