简体   繁体   English

Javascript正则表达式来检测一个字符串是否有两个“ @”字符?

[英]Javascript regex to detect if a string has two “@” chars?

I am trying to do a simple verification that a string contains only one email address. 我正在尝试做一个简单的验证,即一个字符串仅包含一个电子邮件地址。 I am guessing that the easiest way to do this is to look for duplicate "@" chars and reject if that is the case. 我猜想,最简单的方法是查找重复的“ @”字符并在这种情况下拒绝。 I have this code, and I tested the regex on regex101 and it worked perfectly. 我有这段代码,并且我在regex101上测试了regex,它运行良好。 But I'm getting nothing from this now that it's in the page: 但是,由于它在页面中,因此我什么也没得到:

function checkemail(input){
var validformat=/^.*@.*@+.*?/
var returnval=false
if (!validformat.test(input.value))
alert("Invalid email format. Please correct and submit again.")
else{ returnval=true
}
if (returnval==false) input.select()
return returnval
}

And I am calling this with: 我这样称呼:

<form action="storemessage.php" method="POST" onSubmit="return checkemail(this.recipemail)">

And the name of the field is "recipemail." 该字段的名称为“ recipemail”。 Stumped. 难过 Hoping this is something simple that I've just not had enough coffee to see... 希望这很简单,我只是没有足够的咖啡去看...

Regex test returns true if the string matches the format (in your case, if it contains @x2). 如果字符串与格式匹配(在您的情况下,如果它包含@ x2),则正则表达式test返回true。 So you want to change your if condition to act on true values, not false: 因此,您想更改if条件,使其作用于真实值,而不是false:

if (validformat.test(input.value)) {
    alert("Invalid email format. Please correct and submit again.");
}

And perhaps you should rename your regex to invalidformat . 也许您应该将正则表达式重命名为invalidformat

Validating emails in JS is a very tedious task, there are hundreds of weird scenarios you could account for, but it's simply not feasible. 在JS中验证电子邮件是一项非常繁琐的任务,您可以考虑数百种奇怪的情况,但这根本不可行。 So you have to draw the line somewhere. 因此,您必须在某处画线。 Try this regex: 试试这个正则表达式:

/^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM