Prop Validation with Custom Validator Functions
Use a custom validator function to validate a prop's value more thoroughly, beyond the basic type checking.
<div id="app"></div>
HTML placeholder where Vue component will be mounted
/* CSS styles (optional for this example, but included for completeness) */
#app {
font-family: 'Arial', sans-serif;
}
Basic CSS for styling, targeted on the #app element
/* JavaScript using Vue.js framework */
Vue.component('validation-component', {
template: '<div><p v-if="errorMessage">{{ errorMessage }}</p><input :value="value" @input="$emit('input', $event.target.value)"></div>',
props: {
value: {
type: String,
required: true,
validator: function(value) {
// Custom validation logic here
if (value.length < 5) {
this.errorMessage = 'Value must be at least 5 characters long.';
return false;
}
this.errorMessage = '';
return true;
}
}
},
data: function() {
return {
errorMessage: ''
};
}
});
new Vue({
el: '#app',
data: {
myValue: ''
}
});
Vue.js component with custom prop validation. The validator checks if the input value is at least 5 characters long. If not, it sets an error message.