0 day streak
javascript / intermediate
Snippet

Custom Prop Validation for Complex Types

Standard type checks (String, Object) are often insufficient. Custom validators provide a way to enforce business logic on props at runtime, which is especially useful for maintaining data integrity in large applications.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
defineProps({
status: {
type: String,
required: true,
validator(value) {
// Must match one of these specific strings
return ['success', 'warning', 'error', 'loading'].includes(value);
}
},
config: {
type: Object,
validator: (val) => val.id !== undefined && typeof val.retry === 'number'
}
});
vue
Breakdown
1
validator(value) { ... }
A function that returns a boolean to determine if the prop is valid.
2
['success', ...].includes(value)
Ensures the prop value is restricted to a specific set of allowed strings.