Validating props in Vue components

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.

<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.

<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.

<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 -

<!-- 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.

comments powered by Disqus