Vuelidate: Example for using or, and

Created on 15 Feb 2017  路  3Comments  路  Source: vuelidate/vuelidate

I'm trying to use or validations. User need to insert either email or mobile. I could not find any example on your documentation. I'm doing this way. But can't get it working.

import { required, email, or } from 'vuelidate/lib/validators'

  validations: {
        email: {
            email,
            required,
            or: or('mobile')
        },
        mobile: {
            required,
            or: or('email')
        }
    }

Most helpful comment

That's one way, you will get $v.form.$invalid. You can also cross-check between both validations, like

email: {
  email,
  required (v) {
    return this.mobile || required(v)
  }
},
mobile: {
  required (v) {
    return this.email || required(v)
  }
}

Depends on how you want to present the error really.

BTW, that's another reason to implement requiredIf and requiredUnless (#20).

All 3 comments

These validators are simpler than you may expect. They just need two or more validator functions as arguments.

I still don't see how to get it working across different fields in a way similar to yours. @Frizi what do you think?
You may use a custom validator like this.

import { required, email } from 'vuelidate/lib/validators'

    validations: {
        email: {
            email
        },
        mobile: {},
        form: function () { return required(this.email) || required(this.mobile) }
    }

That's one way, you will get $v.form.$invalid. You can also cross-check between both validations, like

email: {
  email,
  required (v) {
    return this.mobile || required(v)
  }
},
mobile: {
  required (v) {
    return this.email || required(v)
  }
}

Depends on how you want to present the error really.

BTW, that's another reason to implement requiredIf and requiredUnless (#20).

@Frizi Thanks for the help. Your solution worked.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

grucha picture grucha  路  4Comments

ecmel picture ecmel  路  3Comments

muchacho-diesel picture muchacho-diesel  路  4Comments

kamaslau picture kamaslau  路  3Comments

pylover picture pylover  路  3Comments