1

Okay, so I'm working on this contact form here, and everything seems to be working well. It checks if the email address has an "@" sign with the following code: (It's a function, just not shown here for ease).

JS:

var at = "@";

if (email.indexOf(at) == -1 || email.indexOf(at) == 0) {
   success = false;
   document.getElementById("email-error").innerHTML = "That's not an email!";
   document.getElementById("email-good").innerHTML = "";
 }

HTML:

<input onfocus="return validation()" type="text" name="email" id="email"><span id="email-error"></span><span id="email-good"></span>

I want to check if there is a "." (dot) in the email value with the following code, but it doesn't work!

  var at = "@";
  var dot = ".";
if (email.indexOf(at) == -1 || email.indexOf(at) == 0 || email.indexOf(dot) == -1 ||    email.indexOf(dot) == 0) {
success = false;
document.getElementById("email-error").innerHTML = "That's not an email!";
document.getElementById("email-good").innerHTML = "";
}

Also, if possible, is there a way to check if there are more than one "@" or "." ? I tried > and != 1 already.

4

3 回答 3

2

有没有办法检查是否有多个“@”或“。” ?

是的,您可以String.prototype.split检查长度

var email = 'a@b.c';

if (email.indexOf('@') < 1 || // @ index -1 or 0
    email.split('@').length > 2 || // more than one @
    email.indexOf('.') < 1) { // . index -1 or 0
    success = false;
    // etc
}

请记住,某些电子邮件地址可以有多个.s,例如someone@ukogbani.co.uk,您无法验证地址是否存在,除非您向其发送内容并获得预期的响应。

一个非常简单的RegExp检查是/^[^ @]+@[^ @]+$/,因为除非它是一个非常特殊的电子邮件地址,否则它不会包含空格或多个@符号,但可以由例如 tld 拥有,com例如tldadmin@com

于 2013-06-14T01:35:51.110 回答
1

如果您尝试使用 javascript 检查有效的电子邮件地址,我强烈建议您使用正则表达式检查。

有关更多信息,请参阅以下帖子:在 JavaScript 中验证电子邮件地址?

于 2013-06-14T01:26:55.623 回答
-1

if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {

   $email = $_POST['email'];
  } 
  else {
  exit("The Email Address you have entered is not valid.");
  }
于 2014-04-04T20:13:55.707 回答