rawmodel/framework

validation of string items in an array of strings

michaelsorich opened this issue · 1 comments

I have a question on how best to set up validation for an array of simple data types (e.g. String or Integer). In the contextablejs readme there is an example for the user tags field being an array of strings (copied below). One can set a presence validator on the array which checks that the array is not empty. However, how does one set validations for the array items - e.g. that Strings in the array cannot be empty? Or if it was an array of integers, the max and min values of the integers contained in the array?

let userSchema = new Schema({
fields: {
...
tags: [
type: ['String'],
defaultValue: ['user'],
validate: [
{
validator: 'presence', // validator name
message: 'is required' // validator error message
}
]
]
}
});

Any insight on how best to do this would be appreciated.

You should add a custom validator.

let userSchema = new Schema({
  fields: {
    tags: {
      type: ['String'],
      validate: [
        {
          validator: 'arrayPresence',
          message: 'all items must be present'
        }
      ]
    }
  },
  validators: {
    arrayPresence (value, recipe) {
      // check `value` for presence
    }
  }
});