【发布时间】:2020-10-20 01:11:24
【问题描述】:
我尝试了几种方法来使材质 UI 的自动完成字段类型成为必需,但我没有得到我想要的行为。我已经将我的字段封装在反应钩子表单<Controller/> 中,但没有运气。当没有任何内容添加到字段时,我想在提交时触发消息“字段为必填项”。
下面是代码sn-p,我没有去掉cmets,这样其他人就更容易理解我之前采用的方法了-
<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" />
【问题讨论】:
-
它可能默认返回空对象,为什么不使用
validate函数。
标签: reactjs material-ui react-hook-form