3
votes

I am working on upgrading from VeeValidate v2 to v3. Since they have removed the ErrorBag concept, I am struggling to figure out how to handle backend validation.

Previously (see code below), I was just running client-side validation, if that passed, call a server validation route, if that failed I would just use the errors.add function in VeeValidate.

Any help would be appreciated. Just need to know to accomplish backend validation handling in VeeValidate v3. Thanks!

validateStep(step) {

this.$validator.validateAll(step).then((result) => {

    // If client-side validation passes, move into this block.
    if (result) {

        // Then run server-side validation.
        axios
            .post(`/ajax/validate-stuff`, this.postData)

            // If server-side validation Passes:
            .then(function (response) {
                // Do the things
            })

            // If server-side validation Fails:
            .catch(function (error) {
                // Add errors to VeeValidate Error Bag
                var entries = Object.entries(error.response.data.errors);
                entries.forEach(function(item, index) {
                    this.Errors.add({
                        field: item[0],
                        msg: item[1][0]
                    });
                });
            });

    }
});

}

2

2 Answers

2
votes

The answer by fylzero above is correct. The important point is to ensure that the vid in the validation provider (below it is 'testinput') matches the key in the error object returned by the server. You then catch the error:

<validation-observer v-slot="{ invalid }" ref="formValidator">
    <form>
        <validation-provider
            v-slot="{ errors }"
            vid="testinput"
        >
            <input />
            <span>{{ errors[0] }}</span>
        </validation-provider>
    </form>
</validation-observer>

<script>
    try {
        // Make the api call here                   

    }
    catch (error) {
        // populate the vee-validate error manually
        this.$refs.formValidator.setErrors(error.data.errors);
    }
</script>
1
votes

I also posted an issue for this in the Github for VeeValidate and was provided the answer.

The documentation for this is, at the time of writing this, buried in the examples section: https://logaretm.github.io/vee-validate/examples/backend.html#server-side-rules

I was told this will be updated in the proper documentation shortly.

Updated Link: https://vee-validate.logaretm.com/v3/advanced/server-side-validation.html#handling-backend-validation