如果仅更改图像,则 React Hook 表单在编辑表单中验证图像

问题描述

在编辑表单中验证图像

我正在使用的软件包:-

  • 反应
  • 反应钩子形式
  • 是的

我的代码运行良好。但是每次编辑表单时都需要上传新图像。 以下表单组件用于事件模型的添加和编辑操作。

我想要达到的目标

我想编辑我的活动标题和地点,但不想编辑我的图片。 所以我没有更新我的图片

但是当我更新图像时,我希望应用验证规则

或者只验证表单的更改字段

如何调用

//Add Form
<EventForms />

//Edit Form
<EventForms edit />

EventForm.js

import React,{ useEffect } from "react";
// import PropTypes from 'prop-types'
import Reactquill from "react-quill";
import "react-quill/dist/quill.sNow.css";
// reactstrap components
import {
  FormGroup,Form,FormText,Input,Row,Col,Container,Card,CardBody,CardHeader,CardTitle,ListGroup,ListGroupItem,Label,Button,} from "reactstrap";
// import { Editor } from "@tinymce/tinymce-react";

import { useForm,Controller } from "react-hook-form";
import { useHistory,useParams } from "react-router-dom";
import { sendForm,viewId,editId } from "../actions/events";
import { usedispatch,useSelector } from "react-redux";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import dayjs from "dayjs";
const FILE_SIZE = "5000000";
const SUPPORTED_FORMATS = ["application/pdf","image/jpeg","image/png"];

function EventForms(props) {
  const schema = yup.object().shape({
    title: yup.string().min(2).max(100).required(),venue: yup.string().min(2).max(100).required(),// description: yup.string().max(700).required(),date: yup
      .string()
      .test("date","Date is not valid",(value) =>
        dayjs(value,"MM/DD/YYYY").isValid()
      )
      .test(
        "Min date","Date Should be After Today",(value) => dayjs(value,"MM/DD/YYYY") > dayjs()
      )
      .required(),time: yup.string().required(),description: yup.string().nullable().required().min(10).max(1000),image: yup
      .mixed()
      .nullable()
      .notrequired()
      .test("FILE_SIZE","Image Is A required Field",(value) => {
        // console.log(value)

        return !value || value.length > 0;
      })
      .test("FILE_SIZE","Image file is too big.",(value) => {
        // console.log(value)
        return (
          !value || (value && value.length > 0 && value[0].size <= FILE_SIZE)
        );
      })
      .test(
        "FILE_FORMAT","Image file has unsupported format.",(value) =>
          !value ||
          (value &&
            value.length > 0 &&
            SUPPORTED_FORMATS.includes(value[0].type))
      ),// status: yup.boolean().required(),});

  const { register,handleSubmit,control,errors,setValue } = useForm({
    resolver: yupResolver(schema),mode: "onChange",});
  const history = useHistory();
  const dispatch = usedispatch();
  const details = useSelector((state) => state.details);

  let { id: reqId } = useParams();
  console.log(details.description);

  useEffect(() => {
    console.log(reqId);
    if (props.edit) {
      dispatch(viewId("event",reqId));
    }
  },[]);

  const onSubmit = (data) => {
    data.date = dayjs(data.date,"MM/DD/YYYY").toISOString();
    data.time = dayjs(
      "1970-00-00 " + data.time,"YYYY-MM-DD hh:mm"
    ).toISOString();

    console.log(data);

    const formdata = new FormData();
    formdata.append("image",data.image[0]);
    formdata.append("date",data.date);
    formdata.append("time",data.time);
    formdata.append("title",data.title);
    formdata.append("description",data.description);
    formdata.append("venue",data.venue);

    console.log(formdata);
    console.log(formdata.title);
    if (props.edit) {
      dispatch(
        editId("event",reqId,formdata,{
          headers: {
            "Content-Type": "multipart/form-data",},})
      );
    } else
      dispatch(
        sendForm("event",})
      );
  };

  return (
    <>
      <Container className="mt--7" fluid>
        <Row className="my-5 ">
          <Col md={12}>
            <Card className="col-lg-10 mx-auto">
              <CardBody>
                <CardTitle tag="h2" className="text-center">
                  Add Event
                </CardTitle>
                <Form onSubmit={handleSubmit(onSubmit)} novalidate>
                  <FormGroup>
                    <Label htmlFor="title">Title: </Label>
                    <Input
                      type="text"
                      placeholder="Enter Event Title"
                      bsSize="sm"
                      autoComplete="off"
                      name="title"
                      id="title"
                      invalid={errors.title !== undefined}
                      innerRef={register()}
                      defaultValue={props.edit ? details.title : null}
                    />
                    {errors.title && (
                      <FormText className="text-capitalize pl-1" color="danger">
                        {errors.title?.message}
                      </FormText>
                    )}
                  </FormGroup>
                  <FormGroup>
                    <Label htmlFor="title">Venue:</Label>
                    <Input
                      type="text"
                      placeholder="Enter Event Venue"
                      bsSize="sm"
                      autoComplete="off"
                      name="venue"
                      id="venue"
                      innerRef={register()}
                      invalid={errors.venue !== undefined}
                      defaultValue={props.edit ? details.venue : null}
                    ></Input>
                    {errors.venue && (
                      <FormText className="text-capitalize pl-1" color="danger">
                        {errors.venue?.message}
                      </FormText>
                    )}
                  </FormGroup>
                  <FormGroup>
                    <Label htmlFor="title">Date:</Label>
                    <Input
                      type="date"
                      placeholder="Enter Date"
                      bsSize="sm"
                      autoComplete="off"
                      name="date"
                      id="date"
                      innerRef={register()}
                      invalid={errors.date !== undefined}
                      defaultValue={
                        props.edit
                          ? dayjs(details.date).format("YYYY-MM-DD")
                          : null
                      }
                    ></Input>
                    {errors.date && (
                      <FormText className="text-capitalize pl-1" color="danger">
                        {errors.date?.message}
                      </FormText>
                    )}
                  </FormGroup>
                  <FormGroup>
                    <Label htmlFor="title">Time:</Label>
                    <Input
                      type="time"
                      placeholder="Enter Time"
                      bsSize="sm"
                      autoComplete="off"
                      name="time"
                      id="time"
                      invalid={errors.time !== undefined}
                      innerRef={register()}
                      defaultValue={
                        props.edit ? dayjs(details.time).format("hh:mm") : null
                      }
                    ></Input>
                    {errors.time && (
                      <FormText className="text-capitalize pl-1" color="danger">
                        {errors.time?.message}
                      </FormText>
                    )}
                  </FormGroup>

                  <FormGroup>
                    <Label htmlFor="title">Description: </Label>

                    <Controller
                      name="description"
                      control={control}
                      defaultValue={props.edit ? details.description : null}
                      render={(props) => (
                        <Reactquill
                          value={props.value || details.description || null}
                          onChange={(e) => props.onChange(e)}
                          theme="sNow"
                          initialValue="dkasjkj"
                          modules={{
                            toolbar: [
                              ["bold","italic"],["link","blockquote","code"],[{ list: "ordered" },{ list: "bullet" }],],}}
                        />
                      )}
                    />
                    {errors.description && (
                      <FormText className="text-capitalize pl-1" color="danger">
                        {errors.description?.message}
                      </FormText>
                    )}
                  </FormGroup>
                  <FormGroup>
                    <Label htmlFor="title">Image:</Label>
                    <Input
                      type="file"
                      autoComplete="off"
                      name="image"
                      id="image"
                      innerRef={register()}
                    ></Input>
                    {errors.image && (
                      <FormText className="text-capitalize pl-1" color="danger">
                        {errors.image?.message}
                      </FormText>
                    )}
                  </FormGroup>

                  <div>
                    <Button type="submit" className="btn btn-primary btn-round">
                      Submit
                    </Button>
                  </div>
                </Form>
              </CardBody>
            </Card>
          </Col>
        </Row>
  </Container>
    </>
  );
}

// EventForms.propTypes = {

// }

export default EventForms;

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...