如何让自定义验证器*检查 Vuejs *props* 中对象的每个属性*
How to make Custom Validator to *check each attribute* of an object in *props* in Vuejs
我有一个名为 car
的道具对象,我想验证 car
的每个属性。
例如规则是:
color
只能是 white
或 black
name
只能是 String
numberOfSits
4 和 2 之间
status
必须是 Available
或 not Available
我知道我需要 car
中的验证器函数 validator (val) =>{}
但 我不知道我应该如何实现它。
我也知道如何检查 String type
道具,例如,如果我有一个 Status
变量,validator
就像:
props:{
Status:{
type: String,
default: 'Available',
validator: function (value : string) {
return ['Available', 'Not Available'].includes(value);
}
}
这是关于我的问题的代码:
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
}
}
我搜索了很多,但没有找到我想要的而且我不想使用任何库
答案很明显,我很想知道为什么你看不到它 - 答案简单地来自问题:
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
}
}
}
我有一个名为 car
的道具对象,我想验证 car
的每个属性。
例如规则是:
color
只能是white
或black
name
只能是String
numberOfSits
4 和 2 之间status
必须是Available
或not Available
我知道我需要 car
中的验证器函数 validator (val) =>{}
但 我不知道我应该如何实现它。
我也知道如何检查 String type
道具,例如,如果我有一个 Status
变量,validator
就像:
props:{
Status:{
type: String,
default: 'Available',
validator: function (value : string) {
return ['Available', 'Not Available'].includes(value);
}
}
这是关于我的问题的代码:
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
}
}
我搜索了很多,但没有找到我想要的而且我不想使用任何库
答案很明显,我很想知道为什么你看不到它 - 答案简单地来自问题:
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
}
}
}