VueJS - Object Props validation VueJS - Object Props validation vue.js vue.js

VueJS - Object Props validation


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.


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.


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;        }    },}