小程序表单验证

下载WxValidate.js

import WxValidate from '../../../utils/WxValidate.js'
Page({
  data: {
    show: true,
    mask: false,
    activityId:'',
   name: "",
    tel: "",
  
  },
  onReady: function (e) {

  },
  onLoad:function(e)
  {
    this.setData({
      activityId:e.activityId
    });
    this.initValidate();
  },
  close(e) {
    this.setData({
      mask: false,
      show:false
    })
  },
  changeName(e){
    this.setData({
      name: e.detail.value,
    })
  },
  changeTel(e){
    this.setData({
      tel: e.detail.value,
    })
  },
  
  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },
  initValidate() {
    const rules = {
      name: {
        required: true,
      },
      tel:{
        required:true,
        tel:true
      }
    }
    const messages = {
      name: {
        required: '请填写姓名',
        minlength:'请输入正确的名称'
      },
      tel:{
        required:'请填写手机号',
        tel:'请填写正确的手机号'
      }
    }
    this.WxValidate = new WxValidate(rules, messages)
  },
  addVolunteerActivityMember(e){
    const params ={name:this.data.name,tel:this.data.tel};
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
      return false
    }
    wx.$api.addVolunteerActivityMember({
      activityId: this.data.activityId,
      name: params.name,
      tel: params.tel
    })
      .then(response => {
        if (response.success) {
          wx.showToast({
            title: "报名成功",
            duration: 2000
          });
          this.setData({
            mask: false
          });
          this.getActivityDetail();
        } else {
          wx.showToast({
            title: response.msg,
            icon: 'error',
            duration: 2000
          });
        }
      })
      .catch(error => {
        console.log(error);
      });
  },

  
})

wxml

<view class="maskBox"   catchtouchmove="preventD" hover-class="none" hover-stop-propagation="false">
    <view class="mask" scroll-top="0"></view>
    <view class="g-center  msg" scroll-top="0">
      <view class="title" scroll-top="0">报名信息</view>
      <view class="input_box" scroll-top="0">
       <span class="">姓名</span>
        <input   class=" " bindinput="changeName" value="{{name}}"   maxlength='13' placeholder="请输入姓名" />
      </view>
      <view   class="input_box"  scroll-top="0">
            <span class="">手机号码</span>
        <input    class=" " bindinput="changeTel" value="{{tel}}"  maxlength='15' placeholder="请输入手机号" />
      </view>
      <view   class="input_box"  scroll-top="0">
              <button class="login-btn" type="primary" bindtap="addVolunteerActivityMember">确定</button>
               <button class="login-btn" type="primary" bindtap="close">取消</button>
      </view>
    </view>
  </view>

 

posted @ 2020-07-08 14:08  艺洁  阅读(208)  评论(0编辑  收藏  举报