小程序表单校验

一.使用WxValidate插件进行表单校验

下载地址https://github.com/18622426238/WxValidate.git

1.test.wxml

<!--pages/test/test.wxml-->
<form bindsubmit='formSubmit'>
<view class="subInfo">
  <view class="subInfoItem clearfix">
    <text class="tag need">校区名称</text>
    <input name='name' value='' placeholder='请输入校区名称' placeholder-class='placeholder'></input>
  </view>
  <view class="subInfoItem clearfix">
    <text class="tag">联系电话</text>
    <input name='contactphone' value='' placeholder='请输入联系电话' placeholder-class='placeholder'></input>
  </view>
</view>
<view class='btnWrap'>
  <button class='saveBtn' form-type='submit'>保存</button>
</view>
</form>

2.test.js

//引入js文件  在utils文件夹下
import WxValidate from '../../utils/WxValidate.js'
var validate;

Page({
  // 初始化表单校验
  initValidate() {
    // 创建实例对象
    this.validate = new WxValidate({
      name: {
        required: true,
        maxlength: 20
      },
      contactphone: {
        required: true,
        tel: true
      }
    }, {
        name: {
          required: '请输入校区名称!',
          maxlength: '名称不得超过20字!'
        },
        contactphone: {
          required: '请输入联系电话!',
          tel: '电话格式不正确!'
        }
      })
  },
  data: {

  },
  onLoad: function (options) {
    this.initValidate()
  },
  formSubmit(e) {
    // 校验表单
    if (!this.validate.checkForm(e.detail.value)) {
      const error = this.validate.errorList[0];
      console.log(error)
      wx.showToast({
        title: `${error.msg} `,
        icon: 'none'
      })
      return false
    }
    // 保存操作...
  }
})

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值