Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 596
felipeecst Avatar asked Apr 18 '17 20:04

felipeecst


1 Answers

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.

like image 146
Egor Stambakio Avatar answered Oct 02 '22 03:10

Egor Stambakio