我想验证上传的表单数量。如果用户上传的文件少于 3 个,点击提交按钮后将显示无效反馈。
据我所知,要统计上传文件的数量,需要使用
Array.from(e.target.files).length
来做条件语句if (Array.from(e.target.files).length < 3)
但是我应该如何在formik的验证中编写该数组和条件语句?
文件上传输入
<Form.Group as={Col} md="4">
<Form.Label>Upload Quotation</Form.Label>
<Form.Control
id="quotation"
name="quotation"
type="file"
multiple
onChange={formik.handleChange}
value={formik.values.quotation}
/>
{formik.errors.quotation ? (
<div>{formik.errors.quotation}</div>
) : null}
</Form.Group>
验证
const validate = (values) => {
// const uploaded = [...uploadedFiles];
const errors = {};
if (!values.edd) {
errors.edd = "Required";
}
if (!values.reason) {
errors.reason = "Required";
}
if (!values.quotation) {
errors.quotation = "Required";
// } else if (number of files uploaded < 3){
// console.log("files uploaded: ", //number of uploaded files)
errors.quotation = "Please upload at least 3 quotations";
}
return errors;
};
在Formik中要实现对上传文件数量的验证,可以使用setFieldValue方法在文件上传时动态更新引用字段的值。您还可以直接从事件对象访问 target.files。
文件上传输入
<form onSubmit={formik.handleSubmit}>
<Form.Group as={Col} md="4">
<Form.Label>Upload Quotation</Form.Label>
<Form.Control
id="quotation"
name="quotation"
type="file"
multiple
onChange={handleFileChange}
onBlur={formik.handleBlur}
/>
{formik.errors.quotation && formik.touched.quotation && (
<div>{formik.errors.quotation}</div>
)}
</Form.Group>
<button type="submit">Submit</button>
</form>
验证
const formik = useFormik({
initialValues: {
edd: '',
reason: '',
quotation: null,
},
validate,
onSubmit: (values) => {
// Your form submission logic here
console.log(values);
},
});
const handleFileChange = (event) => {
formik.setFieldValue('quotation', event.currentTarget.files);
formik.handleChange(event);
};
const validate = (values) => {
const errors = {};
if (!values.edd) {
errors.edd = 'Required';
}
if (!values.reason) {
errors.reason = 'Required';
}
if (!values.quotation || values.quotation.length < 3) {
errors.quotation = 'Please upload at least 3 quotations';
}
return errors;
};
handleFileChange函数负责更新报价字段的值并触发Formik的handleChange方法。
验证函数会检查上传的文件数量是否小于 3,并相应地显示错误。
仅当该字段被触摸时才会显示错误消息,这是由Formik的touched属性控制的。