How to set min property based on another field value (aldeed:simplSchema)

Hello, I need to set min property on a field, but it depends on another field value, the problem is, in the min() function ‘this’ is very limited, so can not say:

new SimpleSchema({
otherField:{
type: Number,
},
field:{
type: Number,
min() {
/*this doesn’t work (this can not accces to siblings fields values here ) */
let minConstraint = this.field(‘otherField’).value ;
return minConstraint;
}
}
})

Instead I need to do it on custom function, but I don’t know how to return min constraint from there, what I’m trying to do is this:

new SimpleSchema({
otherField:{
type: Number,
},
field:{
type: Number,
custom(){
let minConstraint = this.field(‘otherField’).value;
//Return constraint here
return SimpleSchema.Constarint.min = minConstarint;
//Something like that
}
}
})

How can I achieve that,I’ll appreciate any help you can give me

If you wrap your code with triple backticks (```) it will get formatted nicely and makes it much easier for others to read and help you.

You’re almost there with the custom validator! The docs specify that you need to return the validation status from the validation function, not a definition:

All custom validation functions work the same way. First, do the necessary custom validation, use this to get whatever information you need. Then, if valid, return undefined. If invalid, return an error type string. The error type string can be one of the built-in strings or any string you want.

That means you want to examine the value yourself to determine if it’s valid or not in the function:

new SimpleSchema({
  otherField: {
    type: Number,
  },
  field: {
    type: Number,
    custom() {
      let minConstraint = this.field("otherField").value;
      // determine if valid
      const valid = this.value >= minConstraint;
      if (valid) {
        return undefined;
      } else {
        return SimpleSchema.errorTypes.MIN_NUMBER;
      }
    },
  },
});

link: https://github.com/aldeed/simple-schema-js/#custom-field-validation

2 Likes