如何将Vuelidate与自定义验证器一起使用?

时间:2020-10-19 06:01:42

标签: vue.js 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”>
        <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”>
          <div class=“error” v-if=“!$v.formData.vcode.required || !$v.formData.vcode.minLength || !$v.formData.vcode.maxLength”>
            Enter your 6 digit code
          </div>
          <div class=“error” v-if=“!$v.formData.vcode.numeric”>
            Should be a valid value.
          </div>
          <div class=“error” v-if=“!$v.formData.vcode.validCode”>
            Code incorrect, please try again.
          </div>
        </div>
</div>

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

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 {
      }
    },

0 个答案:

没有答案