VueJS - validating object props

In VueJS, how can I validate the type props of an object to ensure that the object has certain specific fields?

For example, I want to make sure that custom support will have field names', 'birthDate', etc.

Thanks in advance.

+3


source to share


2 answers


You can create a custom validation function for objects:

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

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

      

The 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 the validator fails, you will see it Vue warn

in the browser console.

+5


source


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

I check the type of each key that I expect to make sure it matches, in my case, the number. If the key is missing, 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;
        }
    },
}

      

0


source







All Articles