我必须检查表单输入的验证,这是我的代码
//onSave is a button save
const onSave = (event) => {
const invalid = [];
["name", "description", "category"].forEach(key => {
if (key.value.matches("/[0-9]+/)")) {
invalid.push(key);
alert("Not allow number here");
}
});
if (values.name.trim() === "") {
invalid.push("name");
alert("Please not left blank form");
} else {
createProductRequest(values, imageAsFile);
}
};
这就是字段的设定值
const [values, setValues] = useState({
image: "",
name: "",
price: 0,
description: "",
categoty: "",
});
但在我尝试在我的表格中输入数字后,我得到了这个错误
TypeError: Cannot read property 'matches' of undefined`
<Form.Group controlId="name">
<Form.Label>Name</Form.Label>
<Form.Control
type="text"
placeholder="Enter product name"
value={values.name}
name="name"
onChange={handleInputChange}
>
</Form.Control>
</Form.Group>
描述和类别的形式是相同的
有人能解释一下为什么吗?我不知道我错在哪里了?
我查看了您之前的问题,了解您为什么要编写类似的onSave
函数
在你的react应用程序中,你有一个类似的状态
const [values, setValues] = useState({
image: "",
name: "",
price: 0,
description: "",
categoty: "",
});
要访问onSave
函数中的这些值,应将forEach
循环更改为
["name", "description", "category"].forEach(key => {
const value = (typeof values[key] === 'number')
? values[key].toString()
: values[key];
if (value.match(/[0-9]+/)) {
invalid.push(key);
alert("Not allow number here");
}
});
如果有任何错误,要停止推送,您的onSave
功能应该是:
const onSave = (event) => {
const invalid = [];
["name", "description", "category"].forEach(key => {
const value = (typeof values[key] === 'number')
? values[key].toString()
: values[key];
if (value.match(/[0-9]+/)) {
invalid.push(key);
alert("Not allow number here");
}
});
if (values.name.trim() === "") {
invalid.push("name");
alert("Please not left blank form");
}
// Only push to firebase when there are no errors
if (invalid.length === 0) {
createProductRequest(values, imageAsFile);
}
};