微信小程序功能 表单密码强度验证

发布于:2025-08-10 ⋅ 阅读:(17) ⋅ 点赞:(0)

一、页面展示与交互功能

表单提交与验证(含密码强度验证)

实现带密码强度验证的表单提交功能,使用正则表达式检查密码复杂度:

<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位长度

中级要求:包含数字、小写字母、大写字母中的至少两种

高级要求:同时包含数字、小写字母、大写字母和特殊字符(!@#$%^&*)

实时反馈:随着用户输入实时更新密码强度提示

提交验证:最终提交时强制检查是否符合高级要求


网站公告

今日签到

点亮在社区的每一天
去签到