【问题标题】:How to validate checkbox using vuelidate?如何使用 vuelidate 验证复选框?
【发布时间】:2021-08-03 12:24:59
【问题描述】:

我使用 nuxt 创建了一个注册表单,并且表单中有一个复选框。

我应该如何为复选框添加验证?

我正在使用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>

下面是验证代码

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

【问题讨论】:

  • 您正在尝试验证文本输入或复选框?想要接受条款,对吗?你的代码看起来很好。

标签: vue.js nuxt.js vuelidate


【解决方案1】:
validations: {
  form: {
    firstName: {
      required,
      minLength: minLength(2),
      maxLength: maxLength(15),
    },
    acceptTerms: {
      required,
      sameAs: sameAs(() => true), // add this line in validation

    },
  },
},

并在表单中添加错误消息

                           <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>

【讨论】:

    猜你喜欢
    • 2018-12-14
    • 2020-03-21
    • 2021-10-05
    • 2017-05-18
    • 2019-11-01
    • 2021-12-31
    • 2012-01-20
    • 2020-01-05
    • 1970-01-01
    相关资源
    最近更新 更多