I have a Vue form that contains a variable-length record with a language code as key and an object with a repeating structure as value.
const form = reactive({
record: {
en: {foo: 'bar' },
de: {foo: 'baz' }
}
})
Values are added to the record dynamically. I want to add the same rules for each key-value-pair. After looking at the Vuelidate documentation, I only found collection validators which seem to only work for arrays:
const rules = {
record: helpers.forEach({
foo: {required}
})
}
This doesn't work, as the record obviously is no array, so accessing record
on the Vuelidate instance results in an error.
So, what is the intended way of doing this with Vuelidate? I know that I could use an array instead of an object with additional mapping and validation, but I hope there is a simpler way for achieving this.
I realized that Vuelidate rules can be fully reactive, so a solution for me was to make rules a computed that automatically creates the rules for each existing key in the record:
const rules = computed(() => ({
record: Object.keys(form.record).reduce((rules, key) => {
rules[key] = {
required
};
}, {})
}));