Javascript is required
Michael Hoffmann LogoMichael Hoffmann

Vue Tip: Validate Events and Prop Types

Michael Hoffmann - Senior Frontend Developer (Freelancer)
Michael Hoffmann
Mar 28, 2023
1 min read
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:

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

Let's pass an invalid type to the component:

  <Component type="invalid" />

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:

<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

  <button @click="$emit('update')">Update</button>

StackBlitz Example

You can try it yourself in the following StackBlitz project:

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

New Vue & Nuxt tips delivered to your inbox:
I will never share any of your personal data.