JAVASCRIPT

Enforce Data Integrity with Advanced Vue 3 Prop Validation

Ensure robust component interfaces in Vue 3 by implementing advanced prop validation, including type checks, required flags, default values, and custom validators.

// MyValidatedComponent.vue
<template>
  <div>
    <h2>Validated Component</h2>
    <p>User Name: {{ userName }}</p>
    <p>User Age: {{ userAge }}</p>
    <p>Status: {{ userStatus }}</p>
    <p>Registration Date: {{ formattedDate }}</p>
  </div>
</template>

<script setup>
import { computed } from 'vue';

const props = defineProps({
  userName: {
    type: String,
    required: true,
    default: 'Guest'
  },
  userAge: {
    type: Number,
    validator: (value) => {
      return value >= 0 && value <= 150; // Age must be between 0 and 150
    },
    default: 18
  },
  userStatus: {
    type: String,
    validator: (value) => ['active', 'inactive', 'pending'].includes(value),
    default: 'pending'
  },
  registrationDate: {
    type: Date,
    default: () => new Date() // Default value for objects/arrays must be a factory function
  }
});

const formattedDate = computed(() => {
  return props.registrationDate.toLocaleDateString();
});
</script>

// App.vue (Parent Component)
<template>
  <MyValidatedComponent 
    userName="Alice" 
    :userAge="30" 
    userStatus="active" 
  />
  <MyValidatedComponent 
    userName="Bob" 
    :userAge="-5" 
    userStatus="invalid" 
  />
  <MyValidatedComponent />
</template>

<script setup>
import MyValidatedComponent from './MyValidatedComponent.vue';
</script>
How it works: This snippet illustrates how to define and use advanced prop validation in Vue 3. The `defineProps` macro allows you to specify expected data types (`String`, `Number`, `Date`), mark props as `required`, and provide `default` values. For objects or arrays, the default value must be a factory function to prevent shared references. Crucially, custom validation functions can be provided via the `validator` option, allowing complex checks (e.g., age range, specific status values). These validations help catch errors early and ensure components receive predictable data, improving application robustness.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs