之前介紹過微信小程序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 = thislet email = e.detail.value // 獲取輸入框的數據that.setData({email})},confirmTap(){let that = thiswx.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