Vee-validate: 'required_if' extended validation

Created on 7 Mar 2018  ·  3Comments  ·  Source: logaretm/vee-validate

Versions:

  • VueJs: 2.5.7
  • Vee-Validate: 2.0.4

Description:

Hello, I'm trying to create the required-if rule as defined here:
https://laravel.com/docs/5.6/validation#rule-required-if

However, I can't work out how to get the current value of the otherfield.

required_if:{otherfield},{hello}

❔ question

Most helpful comment

It can be tricky to do that in a custom rule, since the required rule is a special rule as it cannot be skipped during validation but custom rules do.

You can achieve this easily with a dynamic expression instead:

<input type="text" name="name" v-validate="{ required: isRequired }">

where isRequired is your condition, for example

export default {
computed: {
    isRequired () {
      return this.fieldValue === 'whatever';
    }
  }
}

or create a dynamic string expression like this example:

https://jsfiddle.net/logaretm/p0766ckj/

All 3 comments

It can be tricky to do that in a custom rule, since the required rule is a special rule as it cannot be skipped during validation but custom rules do.

You can achieve this easily with a dynamic expression instead:

<input type="text" name="name" v-validate="{ required: isRequired }">

where isRequired is your condition, for example

export default {
computed: {
    isRequired () {
      return this.fieldValue === 'whatever';
    }
  }
}

or create a dynamic string expression like this example:

https://jsfiddle.net/logaretm/p0766ckj/

Thanks for the response, this is a good compromise, cheers 👍

Hello,
Is there a way to do this a little bit more programatically? The test below doesn't work.

...
mounted() {
    this.$set(this.formRules.other_amount, 'required', this.isRequiredIf);
},
computed:{
    isRequiredIf() {
        console.log(this.formInputs.amount);
        return this.formInputs.amount === 'other';
    }
}
...
Was this page helpful?
0 / 5 - 0 ratings