我想使用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 = {
'<': '<',
'>': '>',
'&': '&',
'"': '"',
"'": ''',
'/': '/',
};
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;
1条答案
按热度按时间jjjwad0x1#
这就是我解决这个问题的方法。我首先使用下面的代码将替换的符号分派到数据库中
然后使用“he”将htmlEntities解码回浏览器上的符号
//在您的组件中