'VueJS - Object Props validation

In VueJS, how can I validate Object type props in order to ensure that the object has some specific fields defined?

For example, i want to ensure that the user prop will have the fields 'name', 'birthDate', and so on.

Thanks in advance.



Solution 1:[1]

You can create a custom validator function for objects:

https://vuejs.org/v2/guide/components.html#Prop-Validation

props: {
    propF: {
        validator: function (value) {
            return value > 10
        }
    }
}

Function should return true if all fields are present.

Example: https://jsfiddle.net/wostex/63t082p2/27/

<div id="app">
<child :myprop="myObj"></child>
</div>

Vue.component('child', {
    template: `<span>{{ myprop.id }} {{ myprop.name }}</span>`,
    props: {
      myprop: {
        validator: function(obj) {
          return (obj.id && Number.isInteger(obj.id) && obj.name && obj.name.length );
        }
      }
    }
});

new Vue({
    el: '#app',
    data: {
      myObj: {
        id: 10,
        name: 'Joe'
      }
    }
});

If validator fails you will see a Vue warn in browser console.

Solution 2:[2]

There is also a slightly different approach using javascript constructor functions which I show in this example.

It uses the constructor function Person() as a type check. This might result in cleaner code.

Note, however, that otherObj does NOT pass the type check (see the warning in the console) because it does not use the constructor function. This method forces you to use constructor functions instead of objects.

The method is explained in the vue2-docs and vue3-docs.

Solution 3:[3]

Here is an example validator I wrote for one similar case for a property to communicate a display delay for an item that appears on and hides from the screen, in milliseconds. In this case, the property can either be a number for both the "show" and "hide", or it can be an object which defines different delays for each case.

I check the type each key I am expecting to make sure it matches, in my case, 'number'. If a key is missing then the type will be 'undefined'. In my case, negative values are not allowed.

props: {
    delay: {
        type: [Number, Object],
        default: 0,
        validator(value) {
            if (typeof value === 'number') {
                return value >= 0;
            } else if (value !== null && typeof value === 'object') {
                return typeof value.show === 'number' &&
                    typeof value.hide === 'number' &&
                    value.show >= 0 &&
                    value.hide >= 0;
            }

            return false;
        }
    },
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 danronmoon
Solution 2 iron9
Solution 3 SirLamer