首页 > 解决方案 > 如何使材料 UI 的自动完成字段成为必需?

问题描述

我尝试了几种方法来使材料 UI 的自动完成字段类型成为必需,但我没有得到我想要的行为。我已经将我的领域封装在反应钩子形式中<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" />

标签: reactjsmaterial-uireact-hook-form

解决方案


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

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

推荐阅读