之前介绍过微信小程序wxs功能的相关知识:微信小程序:新功能WXS(2017.08.30新增)这里做了一个比较常用的实例:根据检测输入内容格式是否正确,来改变相关显示。 ... ...
这里做了一个比较常用的实例:根据检测输入内容格式是否正确,来改变相关显示。
工具函数:
/src/wxs/common.wxs
-
// 通过正则来检验邮箱是否有效
-
var validateEmail = function(email) {
-
var reg = getRegExp('^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$')
-
return reg.test(email)
-
}
-
module.exports = {
-
validateEmail: validateEmail
-
}
将wxs引入到wxml中,设置module名为util,将data.email绑定到input中,设置相应的事件处理,并根据邮箱检测结果改变相应的class: /pages/checkEmail/checkEmail.wxml
-
src="../../src/wxs/common.wxs" module="util" /> -
class="email_input {{util.validateEmail(email)?'':'error'}}" placeholder='请输入邮箱' value='{{email}}' bindinput='emailInput'>
-
class='button_wrapper'> -
页面js中写好相应事件处理:输入事件emailInput 和 确定事件confirmTap: /pages/checkEmail/checkEmail.js
-
Page({
-
data: {
-
email: ""
-
},
-
emailInput(e){
-
let that = this
-
let email = e.detail.value // 获取输入框的数据
-
that.setData({
-
email
-
})
-
},
-
confirmTap(){
-
let that = this
-
wx.showModal({
-
title: '邮箱',
-
content: that.data.email,
-
showCancel:false
-
})
-
}
-
})
最后是样式设置: /pages/checkEmail/checkEmail.wxss
-
/* input */
-
.email_input {
-
margin: 100rpx auto 0 auto;
-
padding-left: 20rpx;
-
padding-right: 20rpx;
-
width: 400rpx;
-
height: 76rpx;
-
font-size: 28rpx;
-
line-height: 76rpx;
-
background: #F1F1F1;
-
border-radius: 12rpx;
-
}
-
/* 无效邮箱样式 */
-
.email_input.error {
-
border: 2rpx solid red;
-
}
-
/* button */
-
.button_wrapper {
-
margin: 50rpx auto 0 auto;
-
width: 300rpx;
-
}
结果:
测试机效果图 参考: 匹配邮箱正则相关:How to validate email address in JavaScript?
源代码: Github:wechatapp-wxs-tutorial