what is the correct way to add an optional validation object in vuelidate?
Given a validation shape of:
validations: {
vehicles: {
$each: {
type: {
required
},
engine: {
required: requiredIf((vehicle) => vehicle.type == 'car'),
size: {
required
},
power: {
required
}
}
}
}
}
My expectation was that for a vehicle of type bike
I would not need to provide a size and power as their parent engine
is not required. However the validation is returning invalid.
what is the correct way to add an optional validation object in vuelidate?
Given a validation shape of:
validations: {
vehicles: {
$each: {
type: {
required
},
engine: {
required: requiredIf((vehicle) => vehicle.type == 'car'),
size: {
required
},
power: {
required
}
}
}
}
}
My expectation was that for a vehicle of type bike
I would not need to provide a size and power as their parent engine
is not required. However the validation is returning invalid.
- Can you include more of your implementation? Or at least what your model looks like? – LHM Commented Feb 17, 2020 at 18:14
2 Answers
Reset to default 3What you could do instead of asking for each subfield of engine to be required is to ask every engine to have both size
and power
, so that for everytime there is an engine it must have those keys. Add this together with the requiredIf and you have the following: Every vehicle must have a type, if it is a car then an engine is required and every engine must have a power and size
.
The following snippet shows it working.
Vue.use(vuelidate.default);
let { required, requiredIf, helpers } = validators;
const contains = (param) =>
(value) => !helpers.req(value) ||
param.reduce((accum, curr) => accum && curr in value, true);
var app = new Vue({
el: '#app',
data: () => ({
vehicles: [
{
type: 'car',
engine: {
size: 5,
power: 2.5,
}
},
{
type: 'bike',
}
]
}),
validations: {
vehicles: {
$each: {
type: { required },
engine: {
required: requiredIf((value) => value.type === 'car'),
contains: contains(['size', 'power']),
}
}
}
},
created() {
console.log(this.$v.$invalid);
}
});
<script src="https://cdnjs.cloudflare./ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdn.jsdelivr/npm/[email protected]/dist/vuelidate.min.js"></script>
<script src="https://cdn.jsdelivr/npm/[email protected]/dist/validators.min.js"></script>
<div id="app"></div>
I went through a similar situation recently and resolved using 'parentVm', as documented at https://vuelidate.js/#sub-accessing-ponent.
You should try this:
...
engine: {
required: requiredIf((parentVm) => {return parentVm.type === 'car'}),
size: {between: between(yourMinValue, yourMaxValue)},
power: {between: between(yourMinValue, yourMaxValue)},
}
...
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745218196a4617122.html
评论列表(0条)