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

Quasar q-editor富文本编辑器验证规则与样式适配问题

Quasar q-editor 表单验证不生效的解决办法

问题根源

q-editor的v-model绑定的是HTML格式内容,默认空状态下会返回<p></p>这类空标签字符串,直接用!!val判断会被认定为有值,导致必填验证规则失效——这和q-input空值为''的逻辑完全不同。

解决方法

1. 自定义验证规则,过滤空HTML标签

写一个验证函数,先移除所有HTML标签,再判断纯文本内容是否为空:

<template>
  <q-editor 
    v-model="editorContent" 
    min-height="5rem" 
    label="富文本内容"
    :rules="[validateRequired]"
  />
</template>

<script setup>
const editorContent = ref('<p></p>')

const validateRequired = (val) => {
  // 移除所有HTML标签并去除首尾空格
  const plainContent = val.replace(/<[^>]+>/g, '').trim()
  return plainContent.length > 0 || '此字段为必填项'
}
</script>

2. 调整验证触发时机(可选)

如果需要在编辑器失去焦点时才触发验证,添加lazy-rules属性即可:

<q-editor 
  v-model="editorContent" 
  min-height="5rem" 
  label="富文本内容"
  :rules="[validateRequired]"
  lazy-rules
/>

3. 配合q-form全局验证

如果在表单中使用,确保表单能正确触发q-editor的验证逻辑:

<q-form @submit="onSubmit" ref="formRef">
  <q-editor 
    v-model="editorContent" 
    min-height="5rem" 
    label="富文本内容"
    :rules="[validateRequired]"
  />
  <q-btn label="提交" type="submit" />
</q-form>

<script setup>
const formRef = ref(null)
const editorContent = ref('<p></p>')

const validateRequired = (val) => {
  const plainContent = val.replace(/<[^>]+>/g, '').trim()
  return plainContent.length > 0 || '此字段为必填项'
}

const onSubmit = async () => {
  const isValid = await formRef.value.validate()
  if (isValid) {
    // 执行提交逻辑
  }
}
</script>

修改后,q-editor的验证效果会和q-input、q-select完全一致,空内容时会显示错误提示并阻止表单提交。

内容的提问来源于stack exchange,提问作者Morticia A. Addams

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:45:36