Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuelidate requiredUnless - Only one input is required to be filled in

I have three inputs jobApplyEmail, jobApplyPhone, jobApplyOther which I am validating with Vuelidate. Of these three inputs, users are required to enter at least one input. To achieve this I am using requiredUnless however it's not working for some reason.

Template repeated

    // Using bootstrap-vue
    <b-form-input
      id="jobApplyEmail"
      v-model="form.jobApplyEmail"
      type="email"
      :class="{ 'is-invalid': $v.form.jobApplyEmail.$error }"
      @blur="$v.form.jobApplyEmail.$touch()">
    </b-form-input>

Script

    import {
      required,
      email,
      requiredUnless
    } from 'vuelidate/lib/validators'
    data() {
        return {
          form: {
            jobApplyEmail: '',
            jobApplyPhone: '',
            jobApplyOther: ''
          },
        }
      },
    computed: {
        isOptional: () => {
          return (
            this.jobApplyEmail !== '' ||
            this.jobApplyOther !== '' ||
            this.jobApplyPhone !== ''
          )
        }
      },
    
    validations: {
        form: {
          jobApplyEmail: { required: requiredUnless('isOptional'), email },
          jobApplyOther: { required: requiredUnless('isOptional') },
          jobApplyPhone: { required: requiredUnless('isOptional') }
        }
      },

like image 702
Simon Avatar asked Oct 21 '25 09:10

Simon


1 Answers

I solved my question

    jobApplyEmail: {
      requiredIf: requiredUnless(function() {
        return (
          this.form.jobApplyPhone !== '' || this.form.jobApplyOther !== ''
        )
      }),
      email
    },

    jobApplyPhone: {
      requiredIf: requiredUnless(function() {
        return (
          this.form.jobApplyOther !== '' || this.form.jobApplyEmail !== ''
        )
      })
    },
    jobApplyOther: {
      requiredIf: requiredUnless(function() {
        return (
          this.form.jobApplyPhone !== '' || this.form.jobApplyEmail !== ''
        )
      })
    }
like image 120
Simon Avatar answered Oct 23 '25 04:10

Simon