Custom validator function that checks if object properties exist in Vue.js

Sometimes when passing an object as a prop to a Vue component it's important to check if it contains all expected properties. In Vue.js this can be accomplished by writing a custom validator function.

What's expected?

{
  must: true,
  provide: true,
  properties: true
}

Validation:

props: {
  myProp: {
    type: Object,
    required: true,
    validator: (obj) => {
      const missingProperties = [
        'must',
        'provide',
        'properties'
      ].filter((property) => !obj.hasOwnProperty(property));

      return missingProperties.length === 0;
    }
  }
}
Did you like this post?
Previous post

Two ways of testing Vue.js components

I've been working more with Vue.js lately and got familiar with two slightly different ways of testing Vue.js components.