我的自定义Regex电子邮件验证器无法按预期工作



我正在尝试创建一个自定义Regex来验证遵循以下规则的电子邮件:

  1. 电子邮件应以字母表(a-z(开头,不应以特殊字符或数值开头
  2. 在第一个字母之后,它可以包含数字(0-9(、字母(a-z(、下划线(_(和句点(.(
  3. 它应该只有一个@符号
  4. 在@符号之后,它应该只允许包含字母和句点(除了句点(.(之外,没有其他特殊字符或数字(
  5. 电子邮件不应该以句点(.(结尾,而应该以字母表结尾
  6. 它的任何位置都不应该有空格

我有两个数组:trueEmails包含有效的电子邮件,notEmails包含无效的电子邮件。

我创建了以下Regex:

const email = /^[a-zA-Z]+(d|.|w)*@[a-zA-Z]+.[a-zA-Z]+.*[a-zA-Z]+$/;

我的Regex不符合第2、3、4和6条规则。这是我的密码。

const notEmails = [
// rule 1
'_test@email.com',
'#test@email.com',
'1test@email.com',
// rule 2
'test&131@yahoo.com',
// rule 3
'test@gmail@yahoo.com',
// rule 4
'test@yahoo23.com',
// rule 5
'test@yahdsd.com.',
// rule 6
'white space@gmail.com'
]
const trueEmails = [
// rule 1
'test@email.com',
// rule 2
'test2email@yahoo.com',
'test_email@yahoo.com',
'test.123_.emai.l@yahoo.com',
// rule 3
'test@gmail.com',
// rule 4
'testsample@yahoo.co.in',
// rule 5
'testdample232@gmail.com',
// rule 6
'no_white_space@gmail.com'
]
const email = /^[a-zA-Z]+(d|.|w)*@[a-zA-Z]+.[a-zA-Z]+.*[a-zA-Z]+$/;
console.log("NotEmails, should return false")
console.log(notEmails.map((each) => each + ' => ' + email.test(each)));
console.log("trueEmails, should return true")
console.log(trueEmails.map((each) => each + ' => ' +  email.test(each)));

提前谢谢。

我已经更新了正则表达式以适用于您。这不是愚蠢的证明,但适用于你已经实施的限制。

const notEmails = [
// rule 1
'_test@email.com',
'#test@email.com',
'1test@email.com',
// rule 2
'test&131@yahoo.com',
// rule 3
'test@gmail@yahoo.com',
// rule 4
'test@yahoo23.com',
// rule 5
'test@yahdsd.com.',
// rule 6
'white space@gmail.com'
]
const trueEmails = [
// rule 1
'test@email.com',
// rule 2
'test2email@yahoo.com',
'test_email@yahoo.com',
'test.123_.emai.l@yahoo.com',
// rule 3
'test@gmail.com',
// rule 4
'testsample@yahoo.co.in',
// rule 5
'testdample232@gmail.com',
// rule 6
'no_white_space@gmail.com'
]
const email = /^[a-zA-Z]+[a-zA-Z0-9_.]+@[a-zA-Z.]+[a-zA-Z]$/;
console.log("NotEmails, should return false")
console.log(notEmails.map((each) => each + ' => ' + email.test(each)));
console.log("trueEmails, should return true")
console.log(trueEmails.map((each) => each + ' => ' +  email.test(each)));

描述

Regex:/^[a-zA-Z]+[a-zA-Z0-9_.]+@[a-zA-Z.]+[a-zA-Z]$/

  • ^线路起点
  • [a-zA-Z]a-z中的任意字符
  • +一次或多次
  • [a-zA-Z0-9_.]a-z中的任何字符,以及数字、下划线和句点
  • +一次或多次
  • @与文字@符号匹配
  • [a-zA-Z.]+a-z和句点中的任意字符
  • +一次或多次
  • [a-zA-Z]` a-Z中的任何字符
  • $线路末端

最新更新