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

Angular项目PrimeNG p-editor富文本仅空白内容提交校验处理

解决PrimeNG p-editor富文本空白内容校验方案

步骤1:新增富文本非空自定义校验器

在你的组件TS文件或公共校验工具文件中新增校验函数,核心逻辑为去除所有HTML标签后判断剩余内容是否为全空白:

import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';

// 富文本有效内容校验器:去除所有HTML标签后仅剩余空白则判定为无效
export const richTextRequired: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
  if (!control.value) {
    return { error: '公告内容不能为空' };
  }
  // 移除所有HTML标签,再去除首尾空白字符
  const pureText = control.value.replace(/<[^>]*>/g, '').trim();
  return pureText.length === 0 ? { error: '公告内容不能仅包含空白字符' } : null;
};

步骤2:将校验器绑定到表单控件

在addNoticeForm初始化逻辑中,给noticeText字段添加自定义校验器:

import { FormBuilder, FormGroup, Validators } from '@angular/forms';
// 引入上一步定义的richTextRequired校验器

export class YourComponent {
  addNoticeForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.addNoticeForm = this.fb.group({
      // 其余原有表单控件配置保持不变
      companyRole: ['', Validators.required],
      user: ['', Validators.required],
      noticeType: ['', Validators.required],
      noticeStartDate: ['', Validators.required],
      // 给公告内容字段加上自定义校验规则
      noticeText: ['', [Validators.required, richTextRequired]],
      // 其余控件配置保持不变
    });
  }
}

步骤3:校验逻辑对接

你现有代码的错误提示、提交判断逻辑无需大幅修改:

  • HTML中已配置noticeText的错误提示区域,校验不通过时会自动显示对应错误文案
  • 提交逻辑中this.addNoticeForm.valid会自动包含该校验规则,无效内容会直接阻断提交走现有错误处理流程

若需要额外加一层校验保险,可在提交逻辑中补充判断:

onSubmit() {
  this.submitted = true;
  // 额外校验富文本纯内容长度
  const pureNoticeText = this.noticeText?.replace(/<[^>]*>/g, '').trim() || '';
  if (this.addNoticeForm.valid && pureNoticeText.length > 0) {
    // 原有提交逻辑保持不变
  } else {
    this.showError = false;
    this.scrollToErrorField();
  }
}

内容的提问来源于stack exchange,提问作者Shanik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 19:27:03