SimpleSchema: Conditionally required field is not working

狂风中的少年 提交于 2019-12-25 09:28:16

问题


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'

client

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

server

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

But I do get the error "validation-error" with reason "Module is required".

I do not understand that, as you can see module has a value at all!


回答1:


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


来源:https://stackoverflow.com/questions/44943512/simpleschema-conditionally-required-field-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!