1

I am trying to build a kind of specific simple schema for a collection and i would like to make sure that :

when the user enter a new select in my selectsCollection, he will put one of the options value as selected value.

For example:

SelectsCollection.insert({name:"SelectOne",deviceType:"Select",options:["option1","option2","option3"],value:"option4",description:"This is the first select"});

this do not have to work. I want him to write only one of the 3 options.

Here my schema :

SelectsCollection = new Mongo.Collection('Selects'); //Create a table

SelectsSchema = new SimpleSchema({  
    name:{      
        type: String,
        label:"Name",
        unique:true
    },  
    deviceType:{
        type: String,
        allowedValues: ['Select'],
        label:"Type of Device"
    },
    options:{
        type: [String],
        minCount:2,
        maxcount:5,
        label:"Select Values"
    },
    value:{
        type: String,
        //allowedValues:[options] a kind of syntax
        // or allowedValues:function(){ // some instructions to retrieve  the array of string of the option field ?}
        label:"Selected Value"
    },
    description:{
        type: String,
        label:"Description"
    },
    createdAt:{
        type: Date,
        label:"Created At",
        autoValue: function(){
            return new Date()
        }
    } 
});

SelectsCollection.attachSchema(SelectsSchema);

Any Idea ? :)

Thanks a lot !

E.B
  • 141
  • 3
  • 15
  • I don't think this can be done with simple-schema only. Please elaborate why you can't just simply check with plain JS if `value` is in the `options` array? `if(options.indexOf(value) !== -1) { // insert }`. – Patrick DaVader Jun 29 '17 at 19:27
  • I used `if(options.indexOf(value) !== -1) { // insert }` in a custom validation as Khang and you advised :) – E.B Jun 30 '17 at 08:08

1 Answers1

0

This could be done with custom validation function of a field, inside this function you could retrieve values from other fields:

SelectsSchema = new SimpleSchema({
  // ...
  options: {
    type: [String],
    minCount: 2,
    maxcount: 5,
    label: "Select Values"
  },
  value: {
    label: "Selected Value",
    type: String,
    optional: true,
    custom() {
      const options = this.field('options').value
      const value = this.value

      if (!value) {
        return 'required'
      }

      if (options.indexOf(value) === -1) {
        return 'notAllowed'
      }
    }
  },
  // ...
});

Look here custom-field-validation for more information

kkkkkkk
  • 7,628
  • 2
  • 18
  • 31
  • Thank you ! It works ! just one last question about it... what is the meaning of : if (options.indexOf(value) **=== -1**) ? – E.B Jun 30 '17 at 07:59
  • that is used to check if `options` doesn't contain `value` – kkkkkkk Jun 30 '17 at 19:19