如何在Mongoose中使用validator验证字段仅含字母数字与空格
解决Mongoose字段仅允许字母数字与空格的验证问题
你的问题出在validator.isAlphanumeric默认只匹配字母和数字,不包含空格。可以通过两种方式解决:
方案1:使用validator.js的ignore参数
isAlphanumeric方法支持传入ignore选项,指定要允许的额外字符,这里传入空格即可:
const productSchema = new mongoose.Schema({ title: { type: String, required: [true, 'A product must have a Title Bro...'], trim: true, validate: [ { validator: function(v) { return validator.isAlphanumeric(v, 'en-US', { ignore: ' ' }); }, message: 'Only alphanumeric characters and spaces are accepted' } ], maxlength: [50, 'the title must have less or equal than 50 characters'], minlength: [5, 'the title must have more or equal than 5 characters'] } })
方案2:自定义正则表达式验证
如果觉得validator.js的参数不够直观,也可以直接用正则表达式匹配字母数字和空格:
const productSchema = new mongoose.Schema({ title: { type: String, required: [true, 'A product must have a Title Bro...'], trim: true, validate: [ { validator: function(v) { return /^[a-zA-Z0-9\s]+$/.test(v); }, message: 'Only alphanumeric characters and spaces are accepted' } ], maxlength: [50, 'the title must have less or equal than 50 characters'], minlength: [5, 'the title must have more or equal than 5 characters'] } })
说明
- 正则
^[a-zA-Z0-9\s]+$表示:从开头到结尾,只能包含大小写字母、数字和空格,且至少有一个字符。 - 两种方案都能实现需求,可根据习惯选择。
内容的提问来源于stack exchange,提问作者Kiarash P
相关产品推荐
相关产品推荐

