微信小程序--表单验证

表单验证

表单存在多个数据时,数据提交前,对多个数据同时进行验证,验证通过提交,验证失败显示错误数据,一下以单个userTel为例

具体步骤:

  • 1.data中存放4个数据,分别为全局变量isEmpty:truefromData//需要检验的数据,checkData// 校验错误提示,message // 校验不通过提示
data:{
    formData:{},
    checkData:{},
    message:{}, 
    isEmpty:true
}
  • 2.以手机号验证为例:
  <van-field  value="{{ formData.userTel }}" required type="number" label="手机号" placeholder="请填写手机号" border="{{ false }}"  error-message="{{checkData.userTel}}"  name="userTel" data-name="userTel" bind:input="inputValue" />

输入时

  inputValue(e: any) {
    const regexNum = /^1[3456789]\d{9}$/
    var param: string = e.currentTarget.dataset.name; //字段名 
    var value: string = e.detail; //值 
    var key: string = "formData." + param;
    var msg: string = "checkData." + param;
    if (param == 'userTel') {
      if (!regexNum.test(value)) {
        this.setData({
          [key]: value,
          // @ts-ignore
          [msg]: '请输入正确的电话号码格式', //错误提示
        });
      } else {
        this.setData({
          [key]: value,
          // @ts-ignore
          [msg]: '', //错误提示
        });
      }
    }  else {
      this.setData({
        [key]: value,
        [msg]: "" //清空错误提示
      })
    }
  },

提交前

 checkFormData(params: any) {
    let that = this;
    for (let key in params) {
      if (params[key] === '' || params[key].length === 0) {
            that.setData({
              ['formData.' + key]: params[key],
              //@ts-ignore
              ['checkData.' + key]: that.data.message[key].required, //错误提示
            });
          }
         
        } 
   
  },
  getCheckResult() {
    let isEmpty: Boolean = true; // 验证信息是否全空
    let checkData: any = this.data.checkData

    Object.keys(checkData).forEach(function (key) {
      if (checkData[key] !== null && checkData[key] !== undefined && checkData[key] !== '' && checkData[key].length !== 0) {
        isEmpty = false;
      }
    });
    return isEmpty;
  },
  //保存收货人信息
  onSubbmit() {
    let that = this
    this.checkFormData(that.data.formData)
    const checkResult: Boolean = this.getCheckResult();
    if (checkResult) {
      let data: any = that.data.formData
      ApiRequest.postBodyReq(url, data, (resp: Resp<any>) => {
        if (resp.res) {
          wx.showToast({
            title: '新增成功',
            icon: 'success',
            duration: 1000,
            success: function () {
              var pages = getCurrentPages();
              var prevPage = pages[pages.length - 2];
              prevPage.onLoad()
              wx.navigateBack({
                delta: 1,
              })
            }
          })
        }
      })
    }
  },

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