Validating Props in Vue

Published under Vue.

📺  Click here to skip to the video attached to this post  👇

Here's a quick recap on validating props in Vue. All of these examples use Vue's built-in prop validation.

Note: The prop validation does not get bundled when building in a production environment. This means the prop validation acts as a warning during development, but has no impact when shipped to your users.

Validate one or many types

Validate that the name prop must be an (optional) string:

Validate that the name prop must be either an (optional) string or number:

Note: For doing anything other than basic type checking, you need to set the value of your prop to an object. Be aware of the new syntax in the upcoming examples.

Optional vs required props

By default, props in Vue are optional. When an optional prop is not passed into the component, the prop's value will be undefined. If you want to provide a default value for props that are not passed, you can do so via the default key. The following example will set the name prop to "Hello", if name is not passed into the component:

When setting the default value to be either an object or an array, you must ensure to wrap the value in a function. By doing this, you will create a new instance of the object or array for each instance of the component:

If you need a prop to be required, you can remove the default key and replace it with a required boolean value:

Custom validation

Sometimes you will need to perform custom validation on a prop. For example, you may have a status prop that can only be one of three options: pending, in-progress, or complete. Any other value passed into the status prop should be considered invalid.

To run this custom validator, you can use a validator function on the props object. The validator function takes an argument, which is the value of the prop being validated. For our example, the value argument is the value of the status prop:


Make sure you read through Vue's official documentation on prop validation:

Thanks for reading!

Did you find this post useful? Let me know on Twitter! If you found an issue with the content, submit a pull request!

Subscribe to my newsletter to know when I publish more content in the future.

❤️ Likes: 0
📣 Retweets: 0
💬 Replies: 0
🙊 Mentions: 0