Mongoose扩展默认验证
Mongoose expand default validation
我想在猫鼬模式验证规则中构建"minLength"answers"maxLength",目前的解决方案是:
var blogSchema = new Schema({
title: { required: true, type: String }
});
blogSchema.path('title').validate(function(value) {
if (value.length < 8 || value.length > 32) return next(new Error('length'));
});
然而,我认为这应该通过添加自定义模式规则来简化,像这样:
var blogSchema = new Schema({
title: {
type: String,
required: true,
minLength: 8,
maxLength: 32
}
});
我怎么能这样做,这是可能的吗?
查看库猫鼬验证器。它以与您所描述的非常相似的方式集成了节点验证器库,以便在mongoose模式中使用。
具体来说,节点验证器len或min和max方法应该提供所需的逻辑。
试题:
var validate = require('mongoose-validator').validate;
var blogSchema = new Schema({
title: {
type: String,
required: true,
validate: validate('len', 8, 32)
}
});
maxlength和minlength现在存在。您的代码应该如下所示。
var mongoose = require('mongoose');
var blogSchema = new mongoose.Schema({
title: {
type: String,
required: true,
minLength: 8,
maxLength: 32
}
});
我也有相同的功能要求。不知道为什么mongoose不为String类型提供最小/最大值。您可以扩展mongoose的字符串模式类型(我刚刚从数字模式类型复制了min/max函数,并将其适应为字符串-适用于我的项目)。确保在创建模式/模型之前调用补丁:
var mongoose = require('mongoose');
var SchemaString = mongoose.SchemaTypes.String;
SchemaString.prototype.min = function (value) {
if (this.minValidator) {
this.validators = this.validators.filter(function(v){
return v[1] != 'min';
});
}
if (value != null) {
this.validators.push([this.minValidator = function(v) {
if ('undefined' !== typeof v)
return v.length >= value;
}, 'min']);
}
return this;
};
SchemaString.prototype.max = function (value) {
if (this.maxValidator) {
this.validators = this.validators.filter(function(v){
return v[1] != 'max';
});
}
if (value != null) {
this.validators.push([this.maxValidator = function(v) {
if ('undefined' !== typeof v)
return v.length <= value;
}, 'max']);
}
return this;
};
PS:由于这个补丁使用了一些mongoose的内部变量,您应该为您的模型编写单元测试,以注意补丁何时被破坏。
最小值和最大值改变
var breakfastSchema = new Schema({
eggs: {
type: Number,
min: [6, 'Too few eggs'],
max: 12
},
bacon: {
type: Number,
required: [true, 'Why no bacon?']
},
drink: {
type: String,
enum: ['Coffee', 'Tea'],
required: function() {
return this.bacon > 3;
}
}
});
https://mongoosejs.com/docs/validation.html 相关文章:
- Pasleyjs更改欧芹表单验证中按钮的默认行为
- Vanilla javascript 表单验证,如何撤消防止提交时的默认
- 覆盖 AngularJS 默认电子邮件验证器
- j查询验证插件,检查输入默认值
- Jquery 验证 - 需要至少 2 个字段中的 1 个填充默认文本以外的任何内容
- 使用checkValidity进行HTML5表单验证;t显示默认的红色/橙色边框
- 如何在指令的情况下更改下拉列表的默认文本,并对指令应用所需的验证
- 带有默认字段值的Javascript验证
- 使用node.js和angularjs将未经身份验证的用户重定向到默认URL
- 我如何才能以年/月格式验证体验,默认情况下为0.00
- Jquery自定义验证,具有Html 5数据属性和默认值
- 默认情况下,如何制作Express路由需要身份验证
- 如何使用serializeArray()在默认值上验证表单字段
- 用angularjs的形式定义默认值,验证不起作用
- jQuery表单验证- phoneUS和默认消息样式
- 如何在保持JS表单验证功能的同时将默认文本放入输入字段
- 任何使用ASP的默认实体框架验证.净MVC3
- 更改mootools表单验证器的默认错误消息
- 联系人表单默认值验证
- event.prevent验证单选按钮时默认不起作用