meteorsimple-schemameteor-collection2

Aldeed Simple-Schema, how to use allowed values in a field from another one?


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 !


Solution

  • 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