如何在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
相关产品推荐
相关产品推荐

