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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With