自定义表单验证方法的使用

自定义表单验证方法

  1. 自定义表单验证方法适合于简单的验证:
passwordAgain: {
  validator: (rule, value, callback) => {
    console.log(value)
    if (value === "" || value === undefined || value === null) {
      callback(new Error(" "));
    } else if (this.emailForm.password != "" && value == "") {
      callback(new Error(" "));
    } else if (
      this.emailForm.password != "" &&
      value !== this.emailForm.password
    ) {
      callback(new Error(this.$t("validate.passwordMatch")));
    } else {
      callback();
    }
  },
  trigger: "blur"
}
  1. 也可以引入外部的函数来验证
/**
 *  验证手机号
 * @param value
 * @returns {boolean}
 */
export function validateTelephone(value) {
    if (value === undefined || value == null || value === '') return true
    return /^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\d{8}$/.test(
        value
    )
}

import {validateTelephone} from "~/utils/validate" 


telephone:{
  validator: async (rule, value, callback) => {
    if (value === "" || value === undefined || value === null) {
      callback(new Error(" "));
    } else if (this.basicInfoForm.areaCode == "+86" &&
        !validateTelephone(this.basicInfoForm.telephone)) {
      callback(new Error(" "));
    } else {
      try {
        let result = await this.$store.dispatch(
          "API_user/user_checkIdentifier",
          { identifier: value, type: 2 }
        );
        if (result.success) {
          callback();
        } else {
          if (result.errorcode == 1000) {
            this.emailCetshow = true;
          }
          callback(new Error(" "));
        }
      } catch (e) {
        callback(new Error(" "));
        this.$seTip();
      }
    }
  },
  trigger: "blur"
}
posted @ 2020-06-15 09:30  香荣如梦  阅读(709)  评论(0编辑  收藏  举报