You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Quill富文本编辑器字段验证实现咨询

React Quill富文本编辑器字段验证实现咨询

嘿,看你的代码,已经在尝试用Formik结合React Quill做字段验证了,思路很对!我来帮你理清楚这段代码的逻辑,再补充点实用的细节:

一、你当前实现的核心逻辑

这段代码已经覆盖了Formik结合React Quill验证的关键环节:

  • 实时验证触发:在编辑器内容变化时,不仅用formik.setFieldValue更新字段值,还手动调用formik.validateField,这样用户输入过程中就能即时看到验证结果,不用等到提交
  • 触碰状态标记:通过onBlur事件调用formik.setFieldTouched,符合Formik的验证触发规则——只有当用户触碰过字段后,才显示错误
  • 错误样式反馈:动态给编辑器添加inputreactquill-error类名,方便你通过CSS给错误状态的编辑器加边框、背景色这类视觉提示

整理后的完整核心代码如下:

<div className="col-sm-10">
  <ReactQuill
    id="other_detail"
    name="other_detail"
    theme="snow"
    className={`${
      formik.touched.other_detail && formik.errors.other_detail
        ? "inputreactquill-error"
        : ""
    }`}
    value={formik.values.other_detail}
    onChange={(value) => {
      formik.setFieldValue("other_detail", value);
      formik.validateField("other_detail"); // 手动触发实时验证
    }}
    onBlur={() => formik.setFieldTouched("other_detail", true)}
    style={{ height: "180px", marginBottom: 5 }}
  />
  <div className="mt-5">
    {formik.touched.other_detail && formik.errors.other_detail && (
      <span className="text-danger">
        {formik.errors.other_detail}
      </span>
    )}
  </div>
</div>

二、可以优化的地方

  1. 简化错误类名逻辑
    把判断错误的逻辑抽成一个变量,代码会更清晰易读:

    const hasOtherDetailError = formik.touched.other_detail && formik.errors.other_detail;
    
    // 然后ReactQuill的className就可以写成:
    className={`${hasOtherDetailError ? "inputreactquill-error" : ""}`}
    
  2. 更精准的富文本验证
    如果你的验证需要排除HTML标签(比如检查纯文本长度),可以在Formik的验证规则里自定义逻辑,比如用Yup的话:

    import * as Yup from 'yup';
    
    const validationSchema = Yup.object({
      other_detail: Yup.string()
        .required("此字段不能为空")
        .test(
          "plain-text-length",
          "纯文本内容不能少于10个字符",
          (value) => {
            if (!value) return false;
            // 移除所有HTML标签,计算纯文本长度
            const plainText = value.replace(/<[^>]*>/g, "").trim();
            return plainText.length >= 10;
          }
        )
    });
    

这样调整后,你的验证逻辑会更健壮,用户体验也会更顺畅~

备注:内容来源于stack exchange,提问作者Adarsh Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.15 14:29:53