我有一个输入表单,我想在单击“搜索”按钮后验证输入字段。
Most answers I have seen are having the input validated live, as the user enters it into the form.
I don't want to do this as some of the validation I need to do is a costly operation (validating an API key for example), therefore constantly checking it as it's entered is not an option.
This is also a serverless, single page application, and as far as I could tell - onSubmit
would reload the page, so I'm not using that.
我有一个简单的表单,看起来与此类似:
const [formData, setFormData] = useState({});
.......
function handleFormChange(event) {
let data = formData;
data[event.target.name] = event.target.value;
setFormData(data);
}
........
<form id="search-form" >
<TextField name="apiKey" label="API Key" onChange={handleFormChange} defaultValue={formData.apiKey} />
<TextField name='itemName' label="Enter Item" onChange={handleFormChange} />
<Button name='search-button' onClick={validate} >Search</Button>
</form>
I can't work out what to put into validate()
to either set the errors on the text fields or perform the search.
I've tried passing a function into the error
prop that checks to see if an errors
state variable is populated, I've tried looking into using refs to set the error state but I couldn't see any function that would set the error state.
formData变量将保存当前数据,因此很容易检查“此数据是否有效”,但就我的一生而言,我不知道如何手动触发错误状态。
我正在使用React hooks仅供参考
Implement a
validation
function and call it when you submit your form. Maintain a state forerror
and update it when form is invalid. Use material UI error prop to display errors beside your fields.Working demo is here
代码段