likes
comments
collection
share

小程序form表单验证代码实现

作者站长头像
站长
· 阅读数 61

小程序form表单验证,首先我们要下载一个扩展插件WxValidate点击下载

引入 WxValidate.js

将WxValidate.js文件下载下来放入我们的项目中utils目录下:

小程序form表单验证代码实现

在你需要进行操作表单验证的页面的js文件中导入wxValidate.js文件:

小程序form表单验证代码实现

wxml文件设置组件参数绑定,要不无法进行数据验证

小程序form表单验证代码实现

js代码设计

定义name值,定义好后我们接下来进行js校验规则代码设计

首先我们在onLoad中初始化校验:

  onLoad: function (options) {

//初始化验证参数
this.initValidate()

这里我封装了一个方法initValidate()

//表单参数验证
initValidate(){
  const rules = {
    industry: {
      required: true,
    },
    compony:{
      required: true,
    },
    base: {
      required: true,
    },
    job: {
      required: true,
      // minlength:10
    },
    depart: {
      required: true,
      maxlength: 20,
    },
    gotime: {
      required: true,
    },
    downworkTime: {
      required: true,
    },
    aftertime: {
      required: true,
    },
    weekday:{
      required: true
    },
    specialday:{
      required: true,
      maxlength: 20,
    },
    note:{
      required: true,
      maxlength: 20,
    },
    sexpercent:{
      required: false,
      maxlength: 10,
    },
    workpercent:{
      required: false,
      maxlength: 10,
    },
    overtime:{
      required: false,
      maxlength: 100,
    },
    comment:{
      required: false,
      maxlength: 200,
    },
    // phone:{
    //   required:true,
    //   tel:true
    // }
  }
  const messages = {
    industry: {
      required: '请选择行业'
    },
    compony: {
      required: '请选择公司'
    },
    base: {
      required: '请选择base地'
    },
    job: {
      required: '请填写岗位'
    },
    depart: {
      required: '请选择部门',
      maxlength: '部门 最多输入20位'
    },
    gotime: {
      required: '请选择上班时间'
    },
    downworkTime: {
      required: '请选择下班时间'
    },
    aftertime: {
      required: '请选择午休时间'
    },
    weekday:{
      required: '请选择工作天数'
    },
    specialday:{
      required: '周五是否特殊 请填写',
      maxlength: '周五是否特殊 最多输入20位'
    },
    note:{
      required: '请填写日报周报情况',
      maxlength: '日报周报最多输入20位'
    },
    sexpercent:{
      maxlength: '男女生比例最多输入10位'
    },
    workpercent:{
      maxlength: '基层比例最多输入10位'
    },
    overtime:{
      maxlength: '加班情况最多输入100位'
    },
    comment:{
      maxlength: '评价情况最多输入200位'
    },
  }
  this.WxValidate = new WxValidate(rules, messages)
},

自己可以根据实际情况设置字段的具体校验规则,例如是否必填,字段长度等,在wxValidate.js中提供了多种设置规则

小程序form表单验证代码实现

设置成功后就可以在表单提交的方法中调用验证参数进行校验拦截

//表单提交
  formSubmit(e) {
    console.log('form发生了submit事件,携带数据为:', e.detail.value)
//校验表单
if (!this.WxValidate.checkForm(e.detail.value)) {
  const error = this.WxValidate.errorList[0]
  console.log("error_+_+_+_+"+JSON.stringify(error))
  wx.showToast({
    title: error.msg,
    icon: "none",
    duration: 800
  })
  return false
}

整个表单校验的功能就大功告成了,我这里只贴了核心代码,如果读者针对我这些代码自己本地调试出现问题,可与我联系,帮助你进行解决。

转载自:https://juejin.cn/post/7021531160320671752
评论
请登录