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

如何在JSON Schema中为所有字符串字段统一设置禁止含#和!的规则?

统一设置字符串字段的字符限制方案

Mongoose(MongoDB)场景

步骤1:定义通用验证函数

// 验证字符串是否不含#和!
const forbiddenCharsValidator = function(value) {
  return !/#|!/.test(value);
};

步骤2:全局挂载验证规则到字符串类型

直接修改Mongoose内置的String类型验证器,后续所有用String定义的字段都会自动生效:

const mongoose = require('mongoose');
const BaseString = mongoose.Schema.Types.String;

BaseString.set('validate', {
  validator: forbiddenCharsValidator,
  message: props => `${props.path}字段不能包含#或!字符`
});

JSON Schema场景

步骤1:定义可复用的字符串规则片段

在Schema的$defs中抽离通用规则:

{
  "$defs": {
    "safeString": {
      "type": "string",
      "pattern": "^[^#!]*$",
      "errorMessage": "字段不能包含#或!字符"
    }
  }
}

步骤2:批量引用规则

所有字符串字段直接通过$ref引用该片段,无需重复写验证逻辑:

{
  "type": "object",
  "properties": {
    "username": { "$ref": "#/$defs/safeString" },
    "userBio": { "$ref": "#/$defs/safeString" },
    "postContent": { "$ref": "#/$defs/safeString" }
    // 其他字符串字段依此类推
  }
}

通用思路

不管使用哪种Schema工具,核心都是抽离通用验证规则,通过全局配置、继承或引用的方式批量应用,避免在每个字段重复编写相同的限制逻辑,减少维护成本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:44:57