简体   繁体   中英

JavaScript Validation for top level domain of email address

I am trying to create some JavaScript validation to only allow the input of a top level domain of an email address. eg(@gmail.com)

I have used the snippet below to try and form validation around the input, however it still allows full email addresses to be input. eg (mark@gmail.com)

function isEmailDomain(emailDomainVar) {
  var regEmail = new RegExp('@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/');
  return regEmail.test(emailDomainVar);
}

Thanks in advance for any input on this issue!

There is a symbol for matching the beginning of the imput: ^ . Simply add it in the beginning of your regex:

function isEmailDomain(emailDomainVar){
  var regEmail = /^@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;

  return regEmail.test(emailDomainVar);
}

Here is MDN docs ref for further reading.

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