Home > Back-end >  Possible to validate against elements in an array?
Possible to validate against elements in an array?

Time:02-22

I am using validate to validate input, and I need to validate an input that has to be one of the numbers in my arr.

const arr = [1, 2, 4, 5, 9, 14];

const p = {
  System: {
    type: Number,
    enum: arr,
    required: true
  }
};

If I try enum: arr, then it takes the entire array and not just one of the elements.

Question

Is it possible to get validate to use one of the numbers from arr?

CodePudding user response:

import Schema from 'validate'
const arr = [1, 2, 4, 5, 9, 14];

const p_schema = new Schema({
  System: {
    type: Number,
    enum: [...arr],
    required: true
  }
});
let p = {
    System: 9
}

const errors = p_schema.validate(p)

CodePudding user response:

When you specify enum rule, the value of System must be one of the values in the array. The problem with your code however is that you didn't call Scheme from the validate package, so here what you need to change:

import Schema from "validate";

const arr = [1, 2, 4, 5, 9, 14];
const v = new Schema({
  System: {
    type: Number,
    enum: arr,
    required: true,
  },
});

// For testing
const error = v.validate({ System: 3 });

  • Related