Javascript is required
·
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
1<script setup>
2defineProps({
3  type: {
4    type: String,
5    default: 'success',
6    validator(value) {
7      // The value must match one of these strings
8      return ['success', 'warning', 'danger'].includes(value)
9    },
10  },
11})
12</script>

Let's pass an invalid type to the component:

App.vue
1<template>
2  <Component type="invalid" />
3</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
1<script setup>
2const emit = defineEmits({
3  // No validation
4  click: null,
5
6  // Validate update event
7  update: (value) => {
8    if (value) {
9      return true
10    } else {
11      console.warn('Invalid value event payload!')
12      return false
13    }
14  },
15})
16</script>
17
18<template>
19  <button @click="$emit('update')">Update</button>
20</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.