·
1 min read

Vue Tip: Validate Events and Prop Types

Vue Tip: Validate Events and Prop Types Image

You can validate prop types and events in Vue. If a requirement is not met, Vue will warn you in the browser's JavaScript console.

Such validations are typically used if your component is intended to be used by others.

Prop Type Validation

In <script setup>, only the function argument of defineProps() supports custom validator functions (as of Vue 3.2.31).

To specify a prop validation function, you can provide an object with validation requirements to the defineProps() macro:

Component.vue
<script setup> defineProps({ type: { type: String, default: 'success', validator(value) { // The value must match one of these strings return ['success', 'warning', 'danger'].includes(value) }, }, }) </script>

Let's pass an invalid type to the component:

App.vue
<template> <Component type="invalid" /> </template>

Vue will produce a console warning (if using the development build):

Vue Warn

Invalid prop: custom validator check failed for prop "type"

Events Validation

It's also possible to validate an emitted event.

You need to assign a function that receives the emit call's arguments. The function returns a boolean to indicate whether the event is valid or not:

Component.vue
<script setup> const emit = defineEmits({ // No validation click: null, // Validate update event update: (value) => { if (value) { return true } else { console.warn('Invalid value event payload!') return false } }, }) </script> <template> <button @click="$emit('update')">Update</button> </template>

StackBlitz Example

You can try it yourself in the following StackBlitz project:

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.