← Back to Vue.js Course | Chapter 6: Component Communication | Lesson 6 of 7

Prop validation

Prop validation lets a component declare the type, requirement and rules for each prop, with warnings in development.

In this page:

  1. Prop validation
Syntax
markup
props: {
  propName: {
    type: Type,
    required: true,
    default: value,
    validator(value) {
      return condition;
    }
  }
}

Prop validation

Use the object form of props with type, required and validator. Vue warns in development builds when a value does not match. Types include String, Number, Boolean, Array, Object, Function and custom classes, and you can allow several types with an array.

Note: Validation warnings appear only in development builds.

Example: Prop validation

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
  <level-badge :level="3" label="Gold"></level-badge>
  <level-badge level="oops" label="Bad"></level-badge>
</div>
<script>
  const app = Vue.createApp({});
  app.component("level-badge", {
    props: {
      level: { type: Number, required: true, validator: (v) => v >= 1 && v <= 5 },
      label: { type: String, required: true },
    },
    template: "<p>{{ label }}: level {{ level }}</p>",
  });
  app.config.warnHandler = (msg) => console.log("warning:", msg.split("\n")[0]);
  app.mount("#app");
</script>
</body>
</html>

<!-- Output:
Rendered: Gold: level 3Bad: level oops
console: warning: Invalid prop: type check failed for prop "level". Expected Number with value NaN, got String with value "oops".
-->
Live Example
Related Topics
Common Mistakes
  1. Relying on validation for security
  2. Using arrays or objects as defaults directly
  3. Ignoring warnings in the console
Chapter Summary
  • Declare type, required, validator
  • Types can be arrays of types
  • Warnings appear in development
  • Validation is not security
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.