简体   繁体   中英

Check if input value has a “.” (dot) (Javascript)

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.

If you are trying to check for a valid email address using javascript I would strongly recommend using a Regular Expression check.

Please see the following post for more information: Validate email address in JavaScript?

is there a way to check if there are more than one "@" or "." ?

Yes, you can do String.prototype.split and check the length .

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
}

Remember that some email addresses can have multiple . s, eg someone@ukogbani.co.uk and that you can't validate an address exists unless you send something to it and get an expected response.

A really simple RegExp check is /^[^ @]+@[^ @]+$/ , because unless it is a really special email address, it won't contain spaces or more than one @ sign, but could be owned by, eg tld com , such as tldadmin@com

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

   $email = $_POST['email'];
  } 
  else {
  exit("The Email Address you have entered is not valid.");
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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