redux 很难用Yup和Formik进行用户输入验证

ubof19bj  于 2023-03-08  发布在  其他
关注(0)|答案(1)|浏览(163)

我想使用Yup和Formik执行表单验证。最小长度和空字段检查工作正常,但尝试用htmlEntities替换表单中输入的特殊字符没有成功,因为字符仍然会传输到数据库中。请帮助查看我可能做错了什么。谢谢

import { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { getPosts } from "./features/posts/postSlice";
import { createPost } from "./features/poststextonly/postSlice";
import {Formik, Form, Field, ErrorMessage} from "formik";
import * as Yup from "yup";

const sanitizeInput = (input) => {
const regex = /[<>&"']/g;
const htmlEntities = {
  '<': '&lt;',
  '>': '&gt;',
  '&': '&amp;',
  '"': '&quot;',
  "'": '&#x27;',
  '/': '&#x2F',
};
return input.replace(regex, (match) => htmlEntities[match]);
}

const schema = Yup.object().shape({
  pst: Yup.string().min(10, 'Post must be at least 10 characters').required("Field cannot be empty").transform(sanitizeInput),
})

const NewPostForm = () => {
   const dispatch = useDispatch();

   const handleSubmit = (values, {setSubmitting}) => {
    dispatch(createPost(values));
    setSubmitting(false);
    dispatch(getPosts());
   }

  return (
    <Formik initialValues={{pst: ''}} validationSchema={schema} onSubmit={handleSubmit}>
      {({isSubmitting, errors, touched}) => (
        <div className="col-12 mt-1 mb-1">
        <div className="form col-12 mb-0">
          <Form>
            <div className="form-group mb-0 pb-0 ">
              <Field
                as="textarea"
                name="pst"
                id="pst"
                // value={values.pst}
                // onChange={(e) => setPst(e.target.value)}
                className={errors.message && touched.message ? 'error' : ''}
                style={{ backgroundColor: "rgba(0,0,0,.2)" }}
              />
             <ErrorMessage name="pst" component="div" className="error-message bg-danger m-1 text-light" />
            </div>

            <div className="form-group mt-0 col-12 m-0 p-0">
              <button
                className="col-auto btn btn-sm rounded-1 p-1"
                type="submit"
                disabled={isSubmitting}
                style={{
                  marginLeft: "auto",
                  marginRight: "0",
                }}
              >
                {isSubmitting ? "Submitting..." : "Submit"}
              </button>
            </div>
          </Form>
        </div>
      </div>
      )}
      
    </Formik>
  );
};

export default NewPostForm;
jjjwad0x

jjjwad0x1#

这就是我解决这个问题的方法。我首先使用下面的代码将替换的符号分派到数据库中

import { Formik, Form, Field, FieldProps } from 'formik';
import * as Yup from 'yup';

const validationSchema = Yup.object({
  fieldName: Yup.string()
    .required('Field is required')
    .min(10, 'Field must be at least 10 characters')
});

function MyForm() {
  const dispatch = useDispatch();

  function handleSubmit(values, { resetForm }) {
    // Replace special characters with HTML entities
    values.fieldName = values.fieldName.replace(/[&<>"']/g, (match) => {
      switch (match) {
        case '&':
          return '&amp;';
        case '<':
          return '&lt;';
        case '>':
          return '&gt;';
        case '"':
          return '&quot;';
        case "'":
          return '&#039;';
        default:
          return match;
      }
    });

    // Dispatch values to Redux slice
    dispatch(values);

    // Reset form
    resetForm();
  }

  return (
    <Formik
      initialValues={{ fieldName: '' }}
      validationSchema={validationSchema}
      onSubmit={handleSubmit}
    >
      {({ errors, touched, isSubmitting }) => (
        <Form>
          <Field name="fieldName">
            {({ field }: FieldProps) => (
              <div>
                <label htmlFor="fieldName">Field Name</label>
                <textarea id="fieldName" {...field} />
                {errors.fieldName && touched.fieldName && (
                  <div>{errors.fieldName}</div>
                )}
              </div>
            )}
          </Field>

          <button type="submit" disabled={isSubmitting}>
            Submit
          </button>
        </Form>
      )}
    </Formik>
  );
}

export default MyForm;

然后使用“he”将htmlEntities解码回浏览器上的符号

npm install he

//在您的组件中

import he from 'he';

const GetData = ({post}) => {
const decodedText = he.decode(post.post)
     return (
     {decodedText}
     );
}

相关问题