VueJS - validating object props
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.
source to share
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;
}
},
}
source to share