之前介紹過微信小程序wxs功能的相關(guān)知識(shí):微信小程序:新功能WXS(2017.08.30新增)這里做了一個(gè)比較常用的實(shí)例:根據(jù)檢測(cè)輸入內(nèi)容格式是否正確,來改變相關(guān)顯示。 ... ...

這里做了一個(gè)比較常用的實(shí)例:根據(jù)檢測(cè)輸入內(nèi)容格式是否正確,來改變相關(guān)顯示。
工具函數(shù):
/src/wxs/common.wxs
// 通過正則來檢驗(yàn)郵箱是否有效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中,設(shè)置module名為util,將data.email綁定到input中,設(shè)置相應(yīng)的事件處理,并根據(jù)郵箱檢測(cè)結(jié)果改變相應(yīng)的class: /pages/checkEmail/checkEmail.wxml
src="../../src/wxs/common.wxs" module="util" /> class="email_input {{util.validateEmail(email)?'':'error'}}" placeholder='請(qǐng)輸入郵箱' value='{{email}}' bindinput='emailInput'> class='button_wrapper'> 頁(yè)面js中寫好相應(yīng)事件處理:輸入事件emailInput 和 確定事件confirmTap: /pages/checkEmail/checkEmail.js
Page({data: {email: ""},emailInput(e){let that = thislet email = e.detail.value // 獲取輸入框的數(shù)據(jù)that.setData({email})},confirmTap(){let that = thiswx.showModal({title: '郵箱',content: that.data.email,showCancel:false})}})最后是樣式設(shè)置: /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;}結(jié)果:

測(cè)試機(jī)效果圖 參考: 匹配郵箱正則相關(guān):How to validate email address in JavaScript?
源代碼: Github:wechatapp-wxs-tutorial