JavaScript邮箱校验正则如何拦截日文、全角数字等非法字符?
问题原因
原有邮箱正则采用 排除特定非法字符 的逻辑,未对字符范围做半角ASCII限制,日文片假名、全角数字这类Unicode字符不在排除列表中,因此被错误判定为合法字符。
解决方案
在原有邮箱格式校验前,新增半角ASCII字符前置校验,直接拦截所有非半角范围的字符,再保留原有格式校验逻辑即可。
调整后的代码
1. utils.tsx 校验方法修正
export const isEmail = (email: string): boolean => { // 前置校验:仅允许可打印半角ASCII字符,拦截全角、日文、特殊Unicode字符 const isAllHalfAscii = /^[\x20-\x7E]+$/.test(email.trim()); if (!isAllHalfAscii) return false; // 原有邮箱格式校验逻辑保留 const re = /^(([^<>()\[\]\\.,;:\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 re.test(email.toLowerCase()); };
2. Component/index.tsx 顺带修复原有笔误
原组件存在缺失useState导入、value未绑定props字段、事件类型不规范等问题,修正后代码如下:
import React, { useState } from 'react'; import {isEmail} from '../utils' export interface ComponentInterface { emailInput:string setEmailInput: (e: React.ChangeEvent<HTMLInputElement>) => void } const Component : React.FC<ComponentInterface> = (props:ComponentInterface) => { const [inputErrorState, setInputErrorState] = useState(false) const handleOnChange = (e: React.ChangeEvent<HTMLInputElement>) => { if (inputErrorState) { setInputErrorState(false) } props.setEmailInput(e) } const handleOnSubmit = () => { const isValid = isEmail(props.emailInput) setInputErrorState(isValid ? false : true) } return ( <div> <input type='email' id='email-input' value={props.emailInput} onChange={handleOnChange} ></input> {inputErrorState && ( <p>Your error message</p> )} </div> ); } export default Component;
效果验证
- 合法样例
attack.on.titan@gmail.com、black@clover.com会正常通过校验 - 非法样例
ハロー@hello.com、hi123@hello.com、ハロー@ハロー.com会被前置ASCII校验直接拦截,返回false
内容的提问来源于stack exchange,提问作者Alfrex92
相关产品推荐
相关产品推荐

