微信小程序表单验证怎样做,代码是什么
Admin 2022-10-20 群英技术资讯 542 次浏览
在这篇文章中我们来了解一下“微信小程序表单验证怎样做,代码是什么”,一些朋友可能会遇到这方面的问题,对此在下文小编向大家来讲解,内容详细,易于理解,希望大家阅读完这篇能有收获哦,有需要的朋友就往下看吧!
微信小程序的表单验证,供大家参考,具体内容如下
需要用到一个插件WxValidat.js
传送门
在需要使用的page js文件下导入
import WxValidate from '../../utils/WxValidate.js' |
WXML内容
< form bindsubmit = "formSubmit" > < view class = "weui-cells__title" >用户名</ view > < view class = "weui-cells weui-cells_after-title" > < view class = "weui-cell weui-cell_input" > < input class = "weui-input" type = "text" name = "userName" placeholder = "请输入用户名" /> </ view > </ view > < view class = "weui-cells__title" >密码</ view > < view class = "weui-cells weui-cells_after-title" > < view class = "weui-cell weui-cell_input" > < input class = "weui-input" type = "text" name = "password" placeholder = "请输入密码" /> </ view > </ view > < view class = "weui-cells__title" >手机号</ view > < view class = "weui-cells weui-cells_after-title" > < view class = "weui-cell weui-cell_input" > < input class = "weui-input" type = "text" name = "phone" placeholder = "请输入手机号" /> </ view > </ view > < view class = "btn-area" > < button formType = "submit" >Submit</ button > < button formType = "reset" >Reset</ button > </ view > </ form > |
js内容
/** * 生命周期函数--监听页面加载 */ onLoad: function (options) { this .initValidate() //验证规则函数,初始化字段规则和字段提示信息 }, initValidate() { const rules = { userName: { //用户名 required: true , minlength:2 }, password: { //密码 required: true }, phone:{ //手机号 required: true , tel: true } } const messages = { //提示信息 userName: { required: '请填写姓名' , minlength: '请输入正确的名称' }, password: { required: '请填写密码' }, phone:{ required: '请填写手机号' , tel: '请填写正确的手机号' } } this .WxValidate = new WxValidate(rules, messages) }, //调用验证函数 formSubmit: function (e) { console.log( 'form发生了submit事件,携带的数据为:' , e.detail.value) const params = e.detail.value //校验表单 if (! this .WxValidate.checkForm(params)) { const error = this .WxValidate.errorList[0] console.log(error); return false } console.log( "yes" ); return true ; }, |
值得注意的是: WxValidate的errorList列表返回的是一个对象。
而且验证的字段名应该和表单组件对应的name一一对应。
到此,关于“微信小程序表单验证怎样做,代码是什么”的学习就结束了,希望能够解决大家的疑惑,另外大家动手实践也很重要,对大家加深理解和学习很有帮助。如果想要学习更多的相关知识,欢迎关注群英网络,小编每天都会给大家分享实用的文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
目录前言:对象解构示例 {}解构空对象嵌套对象解构前言:使用 JavaScript 对象解构来节省代码,JavaScript 对象解构赋值在项目开发中是一个常用的技能。先来看一个article对象,有两个属性title和description。const article = { title: JavaScript
这篇文章主要介绍了vue 组件基础知识的相关资料,帮助大家更好的理解和使用vue的组件,感兴趣的朋友可以了解下
在本篇文章里小编给大家整理的是一篇关于js定时器出现第一次延迟的原因及解决方法,对此有需要的朋友们可以学习下。
解构赋值是一种特殊的语法,它使我们可以将数组或对象“拆包”为到一系列变量中,因为有时候使用变量更加方便,下面这篇文章主要给大家介绍了关于JavaScript解构赋值的5个常见场景与实例的相关资料,需要的朋友可以参考下
Javascript查看大图功能代码实现,点击小图片可以查看大图,就是把大图放置在顶层(z-index大于当前页面的),并且还可以加一些额外的比如透明度什么的。
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008