一、頁面展示與交互功能
表單提交與驗證(含密碼強度驗證)
實現帶密碼強度驗證的表單提交功能,使用正則表達式檢查密碼復雜度:
<form bindsubmit="submitForm"><input name="username" placeholder="請輸入用戶名" /><input name="password" placeholder="請輸入密碼" type="password" bindinput="checkPasswordStrength" /><!-- 密碼強度提示 --><view class="password-strength">密碼強度:{{passwordStrength}}</view><button form-type="submit">提交</button> </form>
Page({data: {passwordStrength: '未輸入'},// 實時檢查密碼強度checkPasswordStrength(e) {const password = e.detail.value;let strength = '弱'; // 默認弱// 密碼強度正則規則:// 1. 長度至少8位// 2. 包含數字// 3. 包含小寫字母// 4. 包含大寫字母// 5. 包含特殊字符(!@#$%^&*)const lengthRule = /.{8,}/;const hasNumber = /\d/;const hasLowercase = /[a-z]/;const hasUppercase = /[A-Z]/;const hasSpecial = /[!@#$%^&*]/;// 驗證規則并計算強度等級let score = 0;if (lengthRule.test(password)) score++;if (hasNumber.test(password)) score++;if (hasLowercase.test(password)) score++;if (hasUppercase.test(password)) score++;if (hasSpecial.test(password)) score++;// 根據得分設置強度描述if (password.length === 0) {strength = '未輸入';} else if (score < 2) {strength = '弱(至少8位,包含數字和字母)';} else if (score < 4) {strength = '中(建議增加大小寫字母組合)';} else {strength = '強';}this.setData({ passwordStrength: strength });},submitForm(e) {const formData = e.detail.value;// 用戶名驗證if (!formData.username) {wx.showToast({title: '用戶名不能為空',icon: 'none'});return;}// 密碼驗證if (!formData.password) {wx.showToast({title: '密碼不能為空',icon: 'none'});return;}// 密碼強度最終驗證const strongPasswordRule = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*]).{8,}$/;if (!strongPasswordRule.test(formData.password)) {wx.showToast({title: '密碼需8位以上,包含數字、大小寫字母和特殊字符',icon: 'none'duration: 3000});return;}// 驗證通過,提交表單wx.request({url: 'https://api.example.com/register',method: 'POST',data: formData,success: (res) => {if (res.data.success) {wx.showToast({ title: '注冊成功' });} else {wx.showToast({title: '注冊失敗',icon: 'none'});}}});} })
密碼強度驗證規則說明:
基礎要求:至少8位長度
中級要求:包含數字、小寫字母、大寫字母中的至少兩種
高級要求:同時包含數字、小寫字母、大寫字母和特殊字符(!@#$%^&*)
實時反饋:隨著用戶輸入實時更新密碼強度提示
提交驗證:最終提交時強制檢查是否符合高級要求