Vee-validate: conditionally require a field

Created on 24 Mar 2017  路  6Comments  路  Source: logaretm/vee-validate

Currently if the field value is empty, it will pass the validation straightaway by default (except _required_).
However, what I want to achieve is conditional validating empty fields. For example, I have an object {name;'', email:''}, I only want to validate "name" field when "email" field has value.

I wrote a custom validation rule, but it never triggers because empty value will pass the validation directly.

Hopefully it can make some sense. & Thank you for any help and advice

Most helpful comment

you can also do it in the vee-validate attribute

v-validate="<condition> ? 'required|numeric' : '' "

All 6 comments

You should take advantage of the rules being dynamic, meaning you can bind the directive to either a computed property like this:

<input name="email" v-validate="rules" type="text">
export default {
  computed: {
    rules() {
      return this.email.length ? 'required' : '';
    }
  }
};

Or you can also have the rules as an inline template string. Here is a small example on how you might do that:

https://jsfiddle.net/logaretm/eyf8b06q/1/

@logaretm Awesome, exactly what I am looking for. Thank you so much.

you can also do it in the vee-validate attribute

v-validate="<condition> ? 'required|numeric' : '' "

Old closed issue, I know - but if anyone else gets here like I did, the newer computesRequired rule option added here allows for this to be implemented as a validation rule.

live demo

<input v-validate type="text" name="foo" ref="foo" v-validate="'isRequiredWith:bar'">
<input v-validate type="text" name="bar" ref="bar" v-validate="'isRequiredWith:foo'">
import VeeValidate, { Rules } from 'vee-validate';

// changes the behavior of the params passed to the rule callback.
const extendOptions = {
  hasTarget: true,
  computesRequired: true
};

VeeValidate.Validator.extend('isRequiredWith', {
  validate: (value, [other]: any) => {
    const otherFieldHasValue = Rules['required'].validate(String(other).trim());

    if (otherFieldHasValue) {
      const valid =  Rules['required'].validate(String(value).trim());
      return {
        valid:  value,
        data: {
          required: otherFieldHasValue,
        }
      };
    }

    return {
      valid: true,
      data: {
        required: true,
      }
    };
  },
  getMessage: (field, [target]) => `The ${field} field must be set when the ${target} field has a value.`
}, extendOptions);

Thx @emilol! Worth watching this issue :)

Wanted to point directly to the docs:

if you, dear Googler, find this, you will find that it doesnt work for vee-validate v3. Try this instead:

extend('required_if_not', { ...required_if, // params: ['target'] validate: (value, args) => { let target_value = args.target; return Boolean(target_value || value); }, message: 'Bitte dieses Feld ausf眉llen.' });

Was this page helpful?
0 / 5 - 0 ratings