SimpleSchema: Conditionally required field is not

2019-08-27 17:20发布

问题:

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