zoukankan      html  css  js  c++  java
  • 关于小程序表单验证解决方案

    小程序中遇到了表单验证,刚开始想自己写一个正则.但是最后还是使用了

    WxValidate.js这个东西,他只需要将一个js文件放进你的项目,用的时候引用一下,就可以了.非常的方便.
     
    接下来说一下怎么使用,
    1.在github下载WxValidate.js
    2.放入你的项目其中一个文件夹下.
    3.在需要的页面引用下
    import WxValidate from '../vendor/utils/WxValidate.js'
    4. 在onLoad函数中加入
    this.initValidate() //验证规则函数
    5.在onLoad同级放入
    //报错
      showModal(error) {
        wepy.showModal({
          content: error.msg,
          showCancel: false
        })
      }
      //调用验证函数
      formSubmit(e) {
        const params = e
        console.log(this.WxValidate, 'params')
        //校验表单
        if (!this.WxValidate.checkForm(params)) {
          const error = this.WxValidate.errorList[0]
          this.showModal(error)
          return false
        }
        return true
      }
      //验证函数方法
      initValidate() {
        const rules = {
          ProductName: {
            required: true,
            minlength: 1
          },
          Introduce: {
            required: true,
            minlength: 1
          },
          thdata: {
            required: true,
            min: 0
          },
          LendingDays: {
            required: true,
            min: 1
          }
        }
        //函数验证报错信息
        const messages = {
          ProductName: {
            required: '请填写产品名称',
            minlength: '产品名称不能为空'
          },
          Introduce: {
            required: '请填写产品简介',
            minlength: '产品简介不能为空'
          },
          thdata: {
            required: '请填写产品的月基准利率',
            min: '月基准利率只能位数字'
          },
          LendingDays: {
            required: '请填写放款天数',
            min: '放款天数只能为数字'
          }
        }
        this.WxValidate = new WxValidate(rules, messages)
      }
    //需要注意的是
    messages 中的第一行代表为空时的提示信息.第二行代表没有符合验证的提示信息
    //所以第二行的参数:如:min等一定要与上边rules中的第二行的字段保持一致
    //如果用的原生小程序,请在input中加入name='字段名'.如果是组件,如wepy等,将value绑定为字段名即可
    
    

    这段代码

    6.在html中加入

    <view class="submitBtn" @tap="submit({{form}})">提交</view>
    //这里特别注意一下,触发的点击事件中的参数form是一个对象,里面包含了所有需要验证的字段

    7.在submit方法中加入

     let flag = this.formSubmit(e) //调用验证方法
     if (!flag) return
    //这里e为接受到上面传过来的form对象
  • 相关阅读:
    vi常用操作
    Python练习题
    Jmeter也能IP欺骗!
    mysql主从配置
    性能测试之mysql监控、优化
    Git 命令
    Chrome——F12 谷歌开发者工具详解
    Appscan
    微信群发红包抢红包设计测试用例
    MySQL基础篇(1)SQL基础
  • 原文地址:https://www.cnblogs.com/maruihua/p/11394217.html
Copyright © 2011-2022 走看看