是的.mixed().test()在React中无法与Formik一起工作



我已经创建了一个表单,并接受了一些输入,如studentName、photo等。我想验证这些输入。为此,我使用Formik&是的。

  1. 学生名称:-至少3个字符,只允许A-Za-z字符
  2. 照片:-文件不应大于1mb,只有jpeg&允许png文件类型

对studentName的验证工作正常,但对照片无效。当我尝试上传文件时,总是会出现错误,因为上传的文件太大,即使我上传的文件大于1mb。简单地说,以下条件不起作用。

photo: Yup.mixed()
.test('FILE_SIZE', 'Uploaded file is too big.', (value) => !value || (value && value.size >= FILE_SIZE))
.test(
'FILE_FORMAT',
'Uploaded file has unsupported format.',
(value) => !value || (value && SUPPORTED_FORMATS.includes(value.type))
)

Sanbox URL:https://codesandbox.io/s/ecstatic-mountain-gol1l

import "bootstrap/dist/css/bootstrap.min.css";
import { ErrorMessage, Field, Form, Formik } from "formik";
import React from "react";
import * as Yup from "yup";
export default function App() {
const FILE_SIZE = 1000000; //1mb
const SUPPORTED_FORMATS = [
"image/jpg",
"image/jpeg",
"image/png"
];
return (
<div className="App">
<Formik
initialValues={{
studentName: "",
photo: null
}}
validationSchema={Yup.object().shape({
studentName: Yup.string()
.min(3, "Name cannot be less than 3 characters")
.matches(/^[A-Za-z ]*$/, "Please enter valid name")
.required("Student Name is required"),
photo: Yup.mixed()
.required("A file is required")
.test(
"FILE_SIZE",
"Uploaded file is too big.",
(value) => !value || (value && value.size >= FILE_SIZE)
)
.test(
"FILE_FORMAT",
"Uploaded file has unsupported format.",
(value) =>
!value || (value && SUPPORTED_FORMATS.includes(value.type))
)
})}
render={({ errors, touched }) => (
<Form>
<div className="form-group">
<label className="col-sm-4 control-label">Student Name</label>
<div className="col-sm-8">
<Field
id="studentName"
name="studentName"
type="text"
className={
"form-control" +
(errors.studentName && touched.studentName
? " is-invalid"
: "")
}
/>
<ErrorMessage
name="studentName"
component="div"
className="invalid-feedback"
/>
</div>
</div>
<div className="form-group">
<label className="col-sm-4 control-label">Photo</label>
<div className="col-sm-8">
<Field
id="photo"
name="photo"
type="file"
className={
"form-control" +
(errors.photo && touched.photo ? " is-invalid" : "")
}
/>
<ErrorMessage
name="photo"
component="div"
className="invalid-feedback"
/>
</div>
</div>
</Form>
)}
/>
</div>
);
}

我不知道你是否已经解决了这个问题,但对我来说,问题似乎出在这行上

(value) => !value || (value && value.size >= FILE_SIZE)

如果value.size小于FILE_size(而不是像代码中那样大(,则应返回true。

相关内容

  • 没有找到相关文章

最新更新