admin管理员组

文章数量:1136511

I'm making a really simple email validation script that basically just checks the following

  1. that the email isn't blank
  2. the the email contains an @ symbol with at least 1 character before it
  3. that there is a domain ie @ with at least 2 letters after it
  4. that it ends with a fullstop with at least 2 letters after it

I know there are many more checks, but I look at these regex rules and my mind stops working. I figure if I started with something small like this I might be able to wrap my brain around more complex rules.

Currently using some jQuery I do the following:

 var booking_email = $('input[name=booking_email]').val();

 if(booking_email == '' || booking_email.indexOf('@') == -1 || booking_email.indexOf('.') == -1) {

   // perform my alert

 }

This is enough to stop 90% of bogus emails so far... I would just like to make it a bit more effective because currently my rule will allow emails like '@example' or 'user@domain.' because it only checks that there is a fullstop and an @ symbol.

I'm making a really simple email validation script that basically just checks the following

  1. that the email isn't blank
  2. the the email contains an @ symbol with at least 1 character before it
  3. that there is a domain ie @ with at least 2 letters after it
  4. that it ends with a fullstop with at least 2 letters after it

I know there are many more checks, but I look at these regex rules and my mind stops working. I figure if I started with something small like this I might be able to wrap my brain around more complex rules.

Currently using some jQuery I do the following:

 var booking_email = $('input[name=booking_email]').val();

 if(booking_email == '' || booking_email.indexOf('@') == -1 || booking_email.indexOf('.') == -1) {

   // perform my alert

 }

This is enough to stop 90% of bogus emails so far... I would just like to make it a bit more effective because currently my rule will allow emails like '@example.com' or 'user@domain.' because it only checks that there is a fullstop and an @ symbol.

Share Improve this question edited Jul 5, 2022 at 15:23 Stephen Ostermiller 25.5k16 gold badges95 silver badges115 bronze badges asked Feb 11, 2011 at 1:23 willdanceforfunwilldanceforfun 11.2k31 gold badges85 silver badges124 bronze badges 7
  • A tool that might help with RegEx is this Analyzer. – sdleihssirhc Commented Feb 11, 2011 at 1:36
  • 1 u prefer a solution with regex or plain simple javascript ? – Shlomi Komemi Commented Feb 11, 2011 at 1:46
  • 1 plain simple javascript.. regex is probably better but I don't like the unintuitive formatting of it. – willdanceforfun Commented Feb 11, 2011 at 4:26
  • 1 I don't like using code I can't look at and easily understand ie copy and pasting regex stuff. Simply because if I get a complaint about an email not working, I can't look at it simply and get a good idea as to why the script isn't working. – willdanceforfun Commented Feb 11, 2011 at 4:27
  • About two years ago I wrote this: stackoverflow.com/questions/3232/… – some Commented Feb 11, 2011 at 4:48
 |  Show 2 more comments

11 Answers 11

Reset to default 91

What others have suggested should work fine, but if you want to keep things simple, try this:

var booking_email = $('input[name=booking_email]').val();

if( /(.+)@(.+){2,}\.(.+){2,}/.test(booking_email) ){
  // valid email
} else {
  // invalid email
}

Even if you decide to go with something more robust, it should help you understand how simple regex can be at times. :)

The least possible greedy validation you an do is with this RegExp /^\S+@\S+\.\S+$/

It will only ensure that the address fits within the most basic requirements you mentioned: a character before the @ and something before and after the dot in the domain part (\S means "anything but a space"). Validating more than that will probably be wrong (you always have the chance of blacklisting a valid email).

Use it like this:

function maybeValidEmail (email) { return /^\S+@\S+\.\S+$/.test(email); }

Try:

function valid_email(email) {
   return email.match(/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i);
}

That is the best available email validation regex, according to this article. I recommend using this, unless your goal is something really simple but not fully compatible.

RegexLib.com ( http://regexlib.com/Search.aspx?k=email ) has hundreds of email validation routines for a reason. I'd recommend you read this article: http://www.unwrongest.com/blog/email-validation-regular-expressions/ and if you decide to continue using regex for validation, my favorite testing utility is the free regex designer available for free here: http://www.radsoftware.com.au/regexdesigner/ ... test all emails in a LARGE list (available for free download or purchase ... or use your own current DB) to ensure your regex is acceptable within your constraints.

I would recommend a basic test (many at the top of regexlib.com ... I'm not taking credit for the work of theirs I use routinely), followed by a email validation routine that requires user interaction. It is the only real way to 'validate' an email address.

Emails are very difficult to test, but you can have a somewhat restrictive, but simple email validation. I use this one myself, which does a pretty decent job of making sure it's 95% an email address.

var simpleValidEmail = function( email ) {
    return email.length < 256 && /^[^@]+@[^@]{2,}\.[^@]{2,}$/.test(email);
};

I would recommend this for a 'simple' validation.

To see why this is a hard thing to solve, see: How to validate an email address using a regular expression?

Update: corrected regular expression

You can try this:

var booking_email = $('input[name=booking_email]').val();
if(booking_email.match(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/)) {
  // valid email
} else {
  // not valid
}

Based on Ian Christian Myers reply before this, this answer adds + sign and extend to tld with more than 4 chars

function validateEmail(email) {
    const regex = /^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,15}$/;
    return regex.test(email);
}

<input type="email" name="email" required>

This should work I guess.

type = email will check for basic validations and required will check if the field is blank.

You can use a NPM plugin which is very easy to use and is also very powerful. Its super-easy-validator (https://www.npmjs.com/package/super-easy-validator).

Here is how you can use this plugin to check email:

const Validator = require('super-easy-validator')
const rules = { email: 'email' };
const data = { email: booking_email };
const { errors } = Validator.validate(rules, data)
if(errors) {
  console.log(errors);
}

Its not just about email, there are many more features and you can't write every single validator by yourself as its not possible for very large projects. I recommend you to go through the docs of this library, it will save lots of your time in the long run

If you want to check only for Business Emails then try this :

<script type="text/javascript">
$(document).ready(function(e){
     $('#sendReq').click(function(){ 
     var email = $('#emailAddress').val();
     var reg = /^([\w-\.]+@(?!gmail.com)(?!yahoo.com)(?!hotmail.com)(?!yahoo.co.in)(?!aol.com)(?!abc.com)(?!xyz.com)(?!pqr.com)(?!rediffmail.com)(?!live.com)(?!outlook.com)(?!me.com)(?!msn.com)(?!ymail.com)([\w-]+\.)+[\w-]{2,4})?$/;
      if (reg.test(email)){
     return 0;
     }
     else{
     alert('Please Enter Business Email Address');
     return false;
     }
     });
    });
</script>

The is-email package on npm is super simple, if a little loose, just:

var matcher = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;

function isEmail(string) {
  return matcher.test(string);
}

It was written by segment.io, who deal with a lot of emails.

本文标签: jquerySuper simple email validation with JavaScriptStack Overflow