Search code examples
vue.jsvuejs2vuelidate

Accessing validation property outside the current scope in vuelidate/VueJS?


Given the following component in Vue 2 using vuelidate from property validation:

<template>
  // template stuff here...
</template>

<script>
import { validationMixin } from "vuelidate";
import { required, requiredIf } from "vuelidate/lib/validators";

export default {
  name: "ParentComponent",
  mixins: [validationMixin],
  data() {
    return {
      selected: false,
      user: {
        email: null,
        password: null,
      },
    };
  },
  validations: {
    selected: { required },
    user: {
      email: { required: requiredIf((vm) => vm.selected) },
      password: { required: requiredIf((vm) => vm.selected) },
    },
  },
};
</script>

The properties user.email and user.password are required, but only if the validation for selected passes successfully. However, this approach does not seem to work, probably because selected is not part of the user validation object.

Is there a way to access this validation property? Something like this...

 validations: {
    selected: { required },
    user: {
      email: { required: requiredIf((vm) => vm.$parentVm.selected) },
      password: { required: requiredIf((vm) => vm.$parentVm.selected) },
    },
  },

Solution

  • Just like that. Demo https://codesandbox.io/s/green-darkness-90fjs. requiredIf good solution for resolve this problem