【问题标题】:SimpleSchema: Conditionally required field is not workingSimpleSchema:有条件的必填字段不起作用
【发布时间】:2017-07-06 17:12:14
【问题描述】:

这就是我使用带有有条件必填字段 (module) 的 SimpleSchema 进行验证的方式。因此,仅当 type 的值为 '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"

我不明白,正如您所见,module 完全有价值!

【问题讨论】:

    标签: javascript meteor simple-schema


    【解决方案1】:

    发生验证错误是因为您不检查模块是否包含任何值(我对您上一个问题的回答包含错误),所以每次当type 值等于start 时,该方法都会抛出关于必填字段的错误。它甚至不检查 module 字段是否有任何值。我发布了你的固定代码。

    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)
      }
    })
    

    【讨论】:

    • if (!this.isSet || !this.value)还不够吗?
    • 是的,使用if (!this.isSet || !this.value) 就足够了。无论如何,我将保持原样,以便人们更好地理解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 2016-05-22
    • 2012-11-06
    • 2011-05-03
    相关资源
    最近更新 更多