Search code examples
vue.jsnuxt.jsvuelidate

How to validate checkbox using vuelidate?


I created a registration form using nuxt and I have a checkbox in the form.

How should I add validation for the checkbox?

I am using the vuelidate plugin.

<div>
  <div class="form-group">
    <input
      v-model="$v.form.contact.$model"
      :class="status($v.form.contact)"
      name="contact"
      type="contact"
      class="form-control"
      placeholder="Contact"
      @keyup.enter="register"
    />
    <p class="errors">
      <span
        v-if="$v.form.contact.$error"
        class="text-danger"
      >
        <span
          v-if="
            !$v.form.contact.minLength ||
            !$v.form.contact.numeric
          "
          class="text-danger"
        >
          Not a valid contact
        </span>
      </span>
    </p>
  </div>
</div>

<div>
  <input
    name="acceptTerms"
    type="checkbox"
    value=""
  />&nbsp;&nbsp;&nbsp;I agree to the
  <a href="/terms-of-use"> Terms &amp; Conditions </a>
  <p class="errors"></p>
</div>

enter image description here

Below is the code for validation

validations: {
  form: {
    firstName: {
      required,
      minLength: minLength(2),
      maxLength: maxLength(15),
    },
    acceptTerms: {
      required,
    },
  },
},

Solution

  • validations: {
      form: {
        firstName: {
          required,
          minLength: minLength(2),
          maxLength: maxLength(15),
        },
        acceptTerms: {
          required,
          sameAs: sameAs(() => true), // add this line in validation
    
        },
      },
    },
    

    and in form add error message

                               <p class="errors">
                                  <span
                                    v-if="$v.form.acceptTerms.$error"
                                    class="text-danger"
                                  >
                                    <span
                                      v-if="!$v.form.acceptTerms.sameAs"
                                      class="text-danger"
                                    >
                                      Please accept terms and conditions
                                    </span>
                                  </span>
                                </p>