Skip to content Skip to sidebar Skip to footer

Simpleschema: Conditionally Required Field Is Not Working

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 mod

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

Post a Comment for "Simpleschema: Conditionally Required Field Is Not Working"