HTML5与JavaScript中邮箱验证正则表达式报错排查求助
错误原因分析
Chrome控制台抛出的Invalid character in character class错误,根源在于正则表达式的字符类中-的位置不符合ECMAScript语法规范:
- 原正则里的
[a-zA-Z0-9_%+-]和[a-zA-Z0-9._%+-]两个字符类中,-夹在+与其他字符之间。Chrome使用的V8正则引擎(遵循ECMAScript语法)会将这种写法解析为字符范围定义符(类似a-z表示字符范围),但+到-的ASCII范围包含逗号(,)等非预期字符,直接触发语法错误。 - regex101默认可能采用PCRE引擎,该引擎对
-在字符类中的位置限制更宽松,因此未报错,但HTML的pattern属性严格遵循ECMAScript正则语法,因此出现兼容性问题。
另外,原正则中存在重复的断言(?!.*([.-])$),属于冗余代码,可合并简化。
修正后的正则及HTML代码
修正核心动作:
- 将字符类中的
-移到字符类结尾,避免被解析为范围符号 - 合并重复断言,精简正则逻辑
修正后的正则表达式:
^(?!.*([.-])\1)(?!.*[.-]$)(?!.*[.-]{2})[a-zA-Z0-9_%+-.][a-zA-Z0-9._%+-.]*@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
修正后的HTML代码:
<input type="email" pattern="^(?!.*([.-])\1)(?!.*[.-]$)(?!.*[.-]{2})[a-zA-Z0-9_%+-.][a-zA-Z0-9._%+-.]*@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$" />
验证说明
修正后的正则可正确匹配你列出的所有有效邮箱,并排除全部无效邮箱:
有效邮箱匹配:
- email@email.com.eu
- email@example.example.audio
- test@code.email.eu
- example-test@test.email.eu
- test@code-test.com.eu
无效邮箱排除:
- email@em
- email@example.
- test@.code.em.eu
- test@ui.de.
- example.@test.email.eu
- test@-code.example.eu
- test@testmail.com.eu.audio
- code.@code.com
- .test@code.com.audio
- .test@code.com.audio.
- -test@test.code.audio
- -test@test.code.audio-
- 87-code@test-.hi.code
- test/input@test-.com.ar
- ,test@code.com.eu
- email @test.com.eu
内容的提问来源于stack exchange,提问作者A P I
相关产品推荐
相关产品推荐

