通过判断数组中的对象属性是否存在进行表单验证mpvue

通过判断数组中的对象属性是否存在进行表单验证
项目有这么个需求:动态的tab选项卡,通过点击新增按钮来新增选项卡;每个选项卡都有对应的表单数据;点击下一步时需要根据家庭关系来对各个表单中的数据进行正则。
(笔记基于mpvue)

data中的部分

//tab选项卡的内容数据
information:[
        {
          familyRelation: "Main",
          name: "",
          sex: "",
          birthday: "",
          income: null,
          security: ""
        },
	 {
          familyRelation: "Spouse",
          name: "",
          sex: "",
          birthday: "",
          income: null,
          security: ""
        }
],

methods主要代码:

// 判断json的键值是否为null(判断表单中的某些数据是否为空)
findIndexByInformation() {//(点击下一步按钮时调用)
      /* 正则为整数或带小数点的数字 */
      var numReg = /^\d+$|^\d*\.\d+$/;
      var relation = "";
      for (var i = 0; i < this.information.length; i++) {
        if (this.information[i].familyRelation == "Main") {
          relation = "本人";
        } else if (this.information[i].familyRelation == "Spouse") {
          relation = "配偶";
        } else if (this.information[i].familyRelation == "Parent") {
          relation = "父母";
        } else if (this.information[i].familyRelation == "Child") {
          relation = "子女";
        }
        if (this.information[i]["name"] == "") {
          Toast(relation + "姓名必填");
          return i;
        } else if (this.information[i]["sex"] == "") {
          Toast(relation + "性别必填");
          return i;
        } else if (this.information[i]["birthday"] == "") {
          Toast(relation + "出生日期必填");
          return i;
        } else if (this.information[0]["income"] <= 0) {
          Toast("本人年收入(税前)需大于0");
          return i;
        } else if (!numReg.test(this.information[0]["income"])) {
          Toast("本人年收入(税前)必填");
          return i;
        } else if (this.information[0]["security"] == "") {
          Toast("本人社保必填");
          return i;
        } else if (
          this.information[i]["familyRelation"] == "Spouse" &&
          this.information[i]["security"] == ""
        ) {
          Toast("配偶社保必填");
          return i;
        } else if (
          this.information[i]["familyRelation"] == "Parent" &&
          (!this.supportVal || this.supportVal <= 0)
        ) {
          Toast("赡养老人支出/月不能为空且需大于0");
          return i;
        } else if (
          this.information[i]["familyRelation"] == "Child" &&
          (!this.raiseVal || this.raiseVal <= 0)
        ) {
          Toast("抚养子女支出/月不能为空且需大于0");
          return i;
        }
      }
      return null;
    },

 submit(){
	var index = this.findIndexByInformation();
        //  如果所有数据都通过正则(可以调用存数据、跳转页面)
        if (index == null) {
			//在这里调用提交数据的接口
			console.log("ok")
		}
}

主要实现的逻辑:

方法封装:

findIndexByInformation(arr,key){
for(var i=0;i if(arr[i][key] == " "){
return i
}
}
return null
}

调用:
var index=this.findIndexByInformation(this.information,“name”)

你可能感兴趣的:(微信小程序,vue.js,css)