You need to enable JavaScript to run this app. 使用jQuery实现登录页邮箱地址验证时仅执行else分支问题排查
优惠活动
大模型
产品
解决方案
定价
更多

使用jQuery实现登录页邮箱地址验证时仅执行else分支问题排查

邮箱验证逻辑if分支不触发问题修复
  • 核心错误出在正则校验的传参上:你写的reg.test('email')是对固定字符串'email'做校验,而非取你提前定义好的用户输入值变量email,这个固定字符串不符合邮箱规则,所以if分支永远不会触发。
  • 次要问题:你正则里的&是HTML实体转义后的结果,直接放在JS正则里会导致规则失效,需要替换为原始的&字符。

修复后的完整代码如下:

$(document).ready(function () {
    $('#my-input').focusout(function () {
        emailValidate();
    });

    function emailValidate() {
        var reg = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
        var email = $('#my-input').val();
        // 去掉引号使用真实的输入值变量
        if (reg.test(email)) {
            console.log('correct');
            $('#my-input').css('border', '2px solid green');
            $('#span1').css('display', 'none');
        } else {
            $('#my-input').css('border', '2px solid red');
            $('#span1').css('display', 'block');
        }
    }
});

内容的提问来源于stack exchange,提问作者M. R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 03:48:03