有什么方法可以让 Meteor 中的简单模式验证特定的数组索引? [英] Any way to have Simple Schema in Meteor validate a specific array index?
问题描述
根据我在文档中的理解,您可以像这样定义架构:
From what I understand in the docs, you can define your schema like this:
MySchema = new SimpleSchema({
//This says that the addresses key is going to contain an array
addresses: {
type: [Object],
},
// To indicate the presence of an array, use a $:
"addresses.$.street": {
type: String,
},
"addresses.$.city": {
type: String,
}
});
好的,我知道这部分了.但是如果我想验证特定数组索引中的内容怎么办?我想要这样的东西:
Ok, I get this part. But what if I wanted to validate the contents in a specific array index? I want something like this:
MySchema = new SimpleSchema({
//This says that the itemsOrdered key is going to contain an array
itemsOrdered: {
type: [Object],
},
// Here I want to validate certain indexes in the array.
"itemsOrdered.0.sku": {
type: String
},
"itemsOrdered.0.price": {
type: Number
},
"itemsOrdered.1.sku": {
type: String
},
"itemsOrdered.1.price": {
type: Number
},
"itemsOrdered.1.quantity": {
type: Number
},
"itemsOrdered.2.sku": {
type: String
},
"itemsOrdered.2.price": {
type: Number
},
"itemsOrdered.2.customerNotes": {
type: String
optional: true
}
});
所以在这里我尝试验证数组索引 0、1 和 2 中的值.每个数组索引都有一个不同的已排序项.
So here I'm trying to validate the values inside array index 0, 1, and 2. Each array index has a different item that has been ordered.
通常我会使用哈希表数据结构,但为此我需要保留顺序,这就是我使用数组的原因.
Normally I would use a hash table data structure, but for this purpose I need to preserve order which is why I'm using an array.
当我尝试运行此代码时出现错误无法读取未定义的属性blackbox"
When I try to run this code I get an error Cannot read property 'blackbox' of undefined
推荐答案
您是否考虑过自定义验证?https://github.com/aldeed/meteor-simple-schema/blob/master/README.md#custom-validation
Have you considered custom validation? https://github.com/aldeed/meteor-simple-schema/blob/master/README.md#custom-validation
根据函数内的文档,this
的 key
属性将提供您想要的信息.所以你可以有类似的东西:
According to the doc within the function the key
property of this
will provide the information you want. So you could have something like:
MySchema = new SimpleSchema({
//This says that the itemsOrdered key is going to contain an array
itemsOrdered: {
type: [Object],
},
// Here I want to validate certain indexes in the array.
"itemsOrdered.$.sku": {
type: String,
custom: function () {
var key = this.key,
re = /\d+/;
var index = Number(key.match(re)[0]);
// Do some custom validation
}
},
"itemsOrdered.$.price": {
type: Number
},
"itemsOrdered.$.quantity": {
type: Number,
optional: true
},
"itemsOrdered.$.customerNotes": {
type: String,
optional: true
}
});
这里我将验证逻辑放在 sku
字段中,因为它是必需的.
Here I put the validation logic in the sku
field since it's required.
这篇关于有什么方法可以让 Meteor 中的简单模式验证特定的数组索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!