1

Here's the prop's validator:

props: {
    task: {
      id: {
        type: Number,
        validator: function(value) {
          if (value < 5) {
            console.log("error");
            return false;
          }
          return true;
        }
      }

here's the data I'm sending:

export default {
  name: "tasklist",
  data() {
    return {
      tasks: [
        {
          id: 1}

According to the validator I made I shouldn't have it to pass without a warning. And I don't get any warning does anyone knows what I can do to get an error there.

1 Answer 1

1

You can't put a validator or specify the type of a specific property of a component's prop like you are trying to do.

You can specify the type of the task prop as Object, and then add a validator function to validate the type and value of the task object's id property.

Here's an example:

Vue.component('task', {
  template: `<div>{{ task.name }}</div>`,
  props: {
    task: {
      type: Object,
      validator(task) {
        if (typeof task.id !== 'number') {
          console.error("error: task id should be a number");
          return false;
        }
        
        if (task.id < 5) {
          console.error("error: task id should not be less than 5");
          return false;
        }
      }
    }
  }
})

new Vue({ el: '#app' })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.js"></script>
<div id="app">
  <task :task="{ name: 'foo', id: 1 }"></task>
  <task :task="{ name: 'bar', id: '9' }"></task>
  <task :task="{ name: 'baz', id: 6 }"></task>
</div>

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer but I was wondering if there was a way to block it instead of it just showing the error.
Can you be more descriptive? Block what?
I meant is there a built in way to block the insertion as it seems the validation fails I wished it wouldn't insert it if it doesn't respect the condition let's say if the "id" is > 2 don't insert the id.
That's a separate question, but no. There is no built-in way to prevent a component from being created if its prop validation fails. You could simply put the check in a v-if on the root element of the component (<div v-if="task.id >= 5">)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.