Hosseinreza
Hosseinreza

Reputation: 551

How to make Custom Validator to *check each attribute* of an object in *props* in Vuejs

I have a props object named car, I want to validate each attribute of car.
For example, the Rules are:

  1. color must be only white or black
  2. name Must be only String
  3. numberOfSits between 4 and 2
  4. status must be Available or not Available


I know that I need a Validator function in car something like validator (val) =>{} but I don't know how should I implement it .
I also know how to check a String type prop, For example, if I have a Status variable, validator be like :

props:{
  Status:{
    type: String,
    default: 'Available',
    validator: function (value : string) {
      return ['Available', 'Not Available'].includes(value);
    }
}

Here is the Code for my Question:

import { defineComponent } from 'vue'
export default defineComponent({
  name: 'CarComponent',
  data() {
    return {}
  },
  props:{
    Car: {
       type: Object,
       required: true,
       default: () => ({ id: '',name:'',color:'',
         tireSize:'',numberOfSits:'', status: '', engineType: '' 
       }),
       //Validator must be here
     }
  }
});

I searched a lot about it but Didn't find what I want And Also I don't want to use any Library

Upvotes: 1

Views: 866

Answers (1)

IVO GELOV
IVO GELOV

Reputation: 14259

The answer is so obvious that I seriously wonder why you can't see it - the answer simply follows from the question:

import { defineComponent } from 'vue';

export default defineComponent({
  name: 'CarComponent',
  data() {
    return {};
  },
  props: {
    Car: {
      type: Object,
      required: true,
    default: () => ({ 
      id: '',
      name: '',
      color: 'white',
      tireSize: '',
      numberOfSits: 2, 
      status: 'Available', 
      engineType: '' 
    }),
    validator: (value) => {
      return typeof value.name === 'string' &&
        ['white', 'black'].includes(value.color) &&
        ['Available', 'not Available'].includes(value.status) &&
        value.numberOfSits >= 2 && value.numberOfSits <= 4
    }
  }
}

Upvotes: 1

Related Questions