How to validate array of fields using Vuelidate 2 and the Options API in a Vue 3 app

95 Views Asked by At

I am working on a Vue 3 app and I am trying to validate a nested array of fields. I've used the helpers.forEach so far but it does not seem to work for some reason.

Here are my validations:

validations: {
    form: {
        name: {
            required,
            maxLength: maxLength(64),
        },
        location: {
            maxLength: maxLength(191),
        },
        duty_cycle: {
            required,
            integer,
            minValue: minValue(0),
        },
        sensors: {
            $each: helpers.forEach({
                position: {
                    integer,
                    minValue: minValue(0),
                },
                sensor_settings: {
                    $each: helpers.forEach({
                        has_alarm: {
                            boolean: (on_off) => {if (on_off === true || on_off === false) {return true;} else {return false;}},
                        },
                        min_value: {
                            decimal,
                        },
                        max_value: {
                            decimal,
                        },
                    })
                },
            })
        },
    }
},

Here is how I access the errors:

v$.form.sensors.$each.$response.$errors[index].sensor_settings.$each.$response.$errors[i].field_name

but I keep getting:

Cannot read properties of undefined (reading '$response')

when accessing the second $response.

I've browsed through the docs of vuelidate - nothing so far. Googled a ton of things. Even tried ChatGPT and Bard.

Any ideas why that might happen?

1

There are 1 best solutions below

2
Nick Fad On

The problem could be that $response is not present at certain levels, leading to "Cannot read properties of undefined." Try simplifying your validation structure and accessing errors like this:

v$.form.sensors.$each[index].sensor_settings.$each[i].field_name

This assumes that sensors and sensor_settings are arrays, not objects with $each properties. If they are indeed objects, ensure they are initialized properly.

If the issue persists, consider checking the data you're working with during runtime. Sometimes, the error might be due to missing or incorrectly structured data rather than the Vuelidate configuration.

Remember, Vue 3 and Vuelidate 2 might have updates, so checking their documentation or community forums for any specific issues could also be helpful.