Valor_
Valor_

Reputation: 3591

Assign v-validate multiple validation rules (predefined and custom)

I can't figure out how to assign multiple rules to vee-validate. Usualy you pipe | the rules inside v-validate attribute, but the problem is that I also try to include one custom method.

<input id="number" type="tel" v-model="cardDetail.number" v-card-focus
       class="form__input"
       v-validate="'required'" <!-- need to add requireNumberIfCreditCard method -->
       data-vv-validate-on="blur"
       name="number" required>
<label for="number" class="form__label">
    {{ $root.trans.translate('cardNumber') }}
</label>
<p class="form__error" v-show="errors.has('number')">
    {{ errors.first('number') }}
</p>

This is my javascript

export default {
        data() {
            return {
                cardDetail: {
                    number: '',
                }
            }
        },
        computed: {
            requireNumberIfCreditCard() {
                if (this.paymentMethod === 'creditCard') {
                    return this.cardDetail.number ? "required" : "";
                }
            }
        }
    };

How should my HTML look like so I will be also able to add custom mthods to vee-validate? If you need any additional informations, please let me know and I will provide. Thank you!

Upvotes: 2

Views: 2613

Answers (1)

Ryley
Ryley

Reputation: 21216

The attribute v-validate is bound to your data, so you can use anything you want within it. Further, it supports different syntaxes - one, which you're using is a string (i.e. 'required'). Another form it supports is an object, which is what you need:

<input id="number" type="tel" v-model="cardDetail.number" name="number"
       v-validate="{ required: (requireNumberIfCreditCard == 'required') }">

I recommend you change your computed value to return true/false, in which case you can just use it directly.

Working example: https://codesandbox.io/s/km4lw12823

Upvotes: 1

Related Questions