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
I’ve been working more with Vue.js lately and got familiar with two slightly different ways of testing Vue.js components.
Next post

Vue.js adopts a one-way data flow model, which means that state always flows from the parent components to the child components and is usually passed via props. This is a great way of managing state, because it makes things predictable. Ultimately, state needs to be shared between components. This post will explore ways in which parent and child components can share state and most importantly how child components can pass state back to their parents.