3

I am doing an email registration form as a training exercise, and I would like to check with jquery that the address is correct.

so far I have been able to write the following code:

var validateEmail = function(email){
  if(email.includes(' ')){return false};
  if(!email.includes('@')){return false};
  return true;
}

this code works perfectly, but unfortunately the form is validated when there is not the last part of the address, that is to say: ".com" ".fr" etc .. being all new in development if someone could give me a track please :)

I thank you in advance !

Dax
  • 199
  • 1
  • 3
  • 9
  • https://stackoverflow.com/a/44990869/1920003 – Lynob Dec 17 '17 at 09:27
  • Just checking for @ is about the best you can do. You can have a valid e-mail address without tld(eg localhost) and you can have a valid address on IP-addresses. The accepted answer does for example not accept all possible TLD's. Not even thinking about the new TLD's, even some old ones like .museum. And you can't really prevent anyone from writing a fake address anyway. – René Dec 20 '17 at 20:37
  • More info @ https://stackoverflow.com/questions/46155/how-to-validate-email-address-in-javascript (read all :-) ) – René Dec 20 '17 at 20:39

4 Answers4

9

You can use regular javascript

function isEmail(email) {
    var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return regex.test(email);
}
Mohsen
  • 333
  • 2
  • 11
  • 1
    Mohsen, you should change var regex to = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,6})+$/; to support the newer TLD's like .museum, etc. – Naveen Web Solutions Jun 16 '20 at 07:46
6

The emailValidate() function will accept a parameter(sEmail) and using regular expression it will validate the email address. Take help from this code:

function emailValidate(sEmail) {
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    if (filter.test(sEmail)) {
        return true;
    }
    else {
        return false;
    }
}​

Now, you just need to make a call to this function using button click events or so.

kreysix
  • 359
  • 2
  • 11
2

Your validation is a bit simplistic to check for an email. Of course it works without the last part, its because you are only checking for a @ sign.

Instead you can use a more general check using Regular Expressions:

var 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,}))$/;
var isAnEmail = re.test(email.toLowerCase());
Yonatan Naor
  • 1,367
  • 18
  • 19
2

You can do that easily using regex.

var validateEmail = function(email){

var regexForEmailValidation = /^\w+([-+.'][^\s]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;

var emailFormat = regexForEmailValidation.test($(email).val());// this returns result in boolean type

// do whatever you wish to do here
  }
Vikas Yadav
  • 3,094
  • 2
  • 20
  • 21