首页 > 解决方案 > 如何将 Vuelidate 与自定义验证器一起使用?

问题描述

我正在尝试使用 vuelidate 验证 6 位代码。如果 this.validationcode 等于 false 我想显示验证错误。我对 vue 很陌生,所以我不完全确定我哪里出错了。我怎样才能让它工作?

我得到的错误是:

TypeError:无法读取未定义的属性“__isVuelidateAsyncVm”

JS

data() {
    return {
      validationcode: false,
      validationRules: [
        { vcode: { 
            required,
            numeric,
            minLength: minLength(6),
            maxLength: maxLength(6),
            validCode () { return this.validationcode }
          } },
      ],
    };
  },

我也尝试将它作为箭头函数,但它并没有从它的外观正确地获得值。

validCode: () => {
 console.log("the val code is " + this.validationcode)
 return this.validationcode 
}

HTML - v.formData.vcode.validCode - 在当前前端视图中,每次都会触发此规则。

<div class=“form-group”&gt;
        <input
          type=“text”
          class=“form-control”
          :class=“hasError(‘vcode’) ? ‘is-invalid’ : ‘’”
          placeholder=“Enter your 6 digit code”
          v-model=“formData.vcode”
        />
        <div v-if=“hasError(‘vcode’)” class=“invalid-feedback”&gt;
          <div class=“error” v-if=“!$v.formData.vcode.required || !$v.formData.vcode.minLength || !$v.formData.vcode.maxLength”&gt;
            Enter your 6 digit code
          </div>
          <div class=“error” v-if=“!$v.formData.vcode.numeric”&gt;
            Should be a valid value.
          </div>
          <div class=“error” v-if=“!$v.formData.vcode.validCode”&gt;
            Code incorrect, please try again.
          </div>
        </div>
</div>

这是我将 true/false 分配给 this.validationcode 的方法。

verifyNumber() {


      var numbers = /^[0-9]+$/;
      if (code.match(numbers)) {
        // Twilio functions do not accept multipart/form-data
        const data = new URLSearchParams();
        data.append("phone_number", m.mobileNumber);
        data.append("verification_code", code);

        fetch("https://saffron-cheetah-1234.twil.io/check", {
          method: "POST",
          body: data,
        })
          .then((response) => response.json())
          .then((json) => {
            if (json.success) {

              console.log("Successfully verified the token.");
              this.validationcode = true;

            } else {

              this.validationcode = false;
              console.log(this.validationcode);
              console.log("Incorrect token.");
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
      }
    },

标签: vue.jsvuelidate

解决方案


推荐阅读