SimpleSchema:有条件的必填字段不起作用 [英] SimpleSchema: Conditionally required field is not working
问题描述
这就是我使用带有有条件必填字段(module
)的SimpleSchema进行验证的方式.因此,仅当type
的值为'start'
This is how I'm doing a validation using SimpleSchema with a conditionally required field (module
). So this should only be required if type
has the value 'start'
客户
const module = 'articles',
_id = 'bmphCpyHZLhTc74Zp'
console.log(module, _id)
// returns as expected 'articles' and 'bmphCpyHZLhTc74Zp'
example.call(
{
type : 'start',
module: module,
_id : _id
},
(error, result) => {
if (error) console.log(error)
}
)
服务器
example = new ValidatedMethod({
name : 'example',
validate: new SimpleSchema({
_id : { type: SimpleSchema.RegEx.Id },
type: {
type : String,
allowedValues: ['start', 'stop'] },
module: {
type : String,
optional : true,
allowedValues: ['articles'],
custom : function() {
if (this.field('type').value === 'start') return 'required'
return null
}
}
}).validator(),
run({ type, _id, module }) {
console.log(_id, module)
}
})
但是我确实收到错误"validation-error"
,原因为"Module is required"
.
But I do get the error "validation-error"
with reason "Module is required"
.
我不明白这一点,因为您可以看到module
完全有价值!
I do not understand that, as you can see module
has a value at all!
推荐答案
发生验证错误是因为您不检查模块是否包含任何值(我对上一个问题的回答包含错误),因此每次type
值等于start
方法抛出有关必填字段的错误.它甚至不检查module
字段是否具有任何值.我发布了您的固定代码.
The validation error occurs because you don't check if module contains any value(my answer to your previous question contained error), so every time when type
value equals start
the method throw error about a required field. It don't even check if module
field has any value. I post your fixed code.
example = new ValidatedMethod({
name : 'example',
validate: new SimpleSchema({
_id : { type: SimpleSchema.RegEx.Id },
type: {
type: String,
allowedValues: ['start', 'stop']
},
module: {
type: String,
optional: true,
allowedValues: ['articles'],
custom: function() {
if (this.field('type').value === 'start') {
if(!this.isSet || this.value === null || this.value === "") {
return 'required'
}
}
}
}
}).validator(),
run({ type, _id, module }) {
console.log(_id, module)
}
})
这篇关于SimpleSchema:有条件的必填字段不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!