This page looks best with JavaScript enabled

Validating props in Vue components

 ·   ·  ☕ 2 min read

Validate your props in Vue components.

We have seen all about props in Vue before. We can define a simple prop in a component, pass the value from source, and the receiving component happily processes it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<template>
  <div>{{ contactDetails }}</div>
</template>

<script>
  export default {
    data: () => ({}),

    props: {
      contactDetails: {
        type: String,
        required: true
      }
    }
  };
</script>

But, what if you want to validate the prop? We have certainly seen the warnings when we do not pass the prop of the expected type or when not supplying a mandatory prop.

How about other validations? How about objects that do not subject themselves to such validations?

Turns out - that is easy as well. We can use a validator object and specify a function that does any validation for us.

For e.g. check whether the given name is at least 10 characters long.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<template>
  <div>{{ contactDetails }}</div>
</template>

<script>
  export default {
    data: () => ({}),

    props: {
      contactDetails: {
        type: String,
        required: true,
        validator: val => val.length >= 10
      }
    }
  };
</script>

The validation throws warnings when not satisfied - similar to all the other prop warnings.

vue-prop-validator-warning

We can apply validation to more complex objects as well.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<template>
  <div>{{ contactDetails }}</div>
</template>

<script>
  export default {
    data: () => ({}),

    props: {
      contactDetails: {
        type: Object,
        validator: val => val.location != "Chile"
      }
    }
  };
</script>

We call the above component like so -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!-- Caller -->
<template>
  <div>
    <v-container grid-list-xs>
      <PropReceiver :contactDetails="contact"></PropReceiver>
    </v-container>
  </div>
</template>

<script>
  import PropReceiver from "../components/PropReceiver";

  export default {
    data: () => ({
      contact: {
        firstName: "John",
        lastName: "Doe",
        location: "Chile"
      }
    }),
    components: {
      PropReceiver
    }
  };
</script>

Validator is handy piece of functionality to validate input props and respond to the many complex prop-situations - as they arise.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things