28

I would like that email had format like: [email protected].

Which is the best way to do it?

I have a component for registration and I have the field like this:

<mat-form-field>
              <input matInput placeholder="Email" name="email" [(ngModel)]="email" required>
</mat-form-field>

In my usersRouter I have the function for registration:

router.post('/users/register', (req, res) => {
        ...
        const user = new User({
            ...
            email: req.body.email,
            ...
        });
     ...
});

Also, I use mongo and in the UserSchema I have this for the email:

email: {
        type: String,
        required: true
}

Thanks!

1

5 Answers 5

31

You can use email validator module:

var validator = require("email-validator");
validator.validate("[email protected]");

Or, if you don't want any dependencies:

var emailRegex = /^[-!#$%&'*+\/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/;

function isEmailValid(email) {
    if (!email)
        return false;

    if(email.length>254)
        return false;

    var valid = emailRegex.test(email);
    if(!valid)
        return false;

    // Further checking of some things regex can't handle
    var parts = email.split("@");
    if(parts[0].length>64)
        return false;

    var domainParts = parts[1].split(".");
    if(domainParts.some(function(part) { return part.length>63; }))
        return false;

    return true;
}

Source:

https://www.npmjs.com/package/email-validator

https://github.com/manishsaraan/email-validator/blob/master/index.js

Sign up to request clarification or add additional context in comments.

2 Comments

there is a problem with timeout. I use email-validator but sometime it show an error as "{"message":"Please provide a valid email address.","reason":"Timeout"}" so my question is how to get rid of this timeout error. Note: when I send mail to this same address by usying gmail account, it is sending.
email-validator fails on 7 of these addresses: codefool.tumblr.com/post/15288874550/…
22

Use regular expression something like that:

Solution 1:

^[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])?)*$

Sample code:

const emailToValidate = '[email protected]';
const emailRegexp = /^[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])?)*$/;

console.log(emailRegexp.test(emailToValidate));

Solution 2:

Because you use angular, you are able to validate the email on front-end side by using Validators.email.

If you check angular source code of Validators.email here, you will find an EMAIL_REGEXP const variable with the following value:

/^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[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])?)*$/;

You could use it on back-end side too, to validate the input.

1 Comment

Bear in mind that the above solutions allows emails without TLD, like this: a@a
5

I like validator.js

from the docs:

var validator = require('validator');

validator.isEmail('[email protected]');

source: https://www.npmjs.com/package/validator

Comments

3

In my project i've used email-validator module

npm i email-validator


const emailvalidator = require("email-validator");
if(emailvalidator.validate(req.body.email)){
      // Your call to model here
}else{
   res.status(400).send('Invalid Email');
}

You can install the module from below link

https://www.npmjs.com/package/email-validator

2 Comments

there is a problem with timeout. I use email-validator but sometime it show an error as "{"message":"Please provide a valid email address.","reason":"Timeout"}" so my question is how to get rid of this timeout error. Note: when I send mail to this same address by usying gmail account, it is sending.
@MuhammadAbubakarZorrain, it seems to be a bug, you can open an issue in the github repository. github.com/manishsaraan/email-validator/issues
0

I like the Joi library for those. Enables you to validate all kinds of things easily!

const Joi = require('joi');

const schema = Joi.string().email().trim();

// "[email protected]"
const validEmail = Joi.attempt('[email protected]', schema);

// trimmed "[email protected]"
const validEmail = Joi.attempt(' [email protected] ', schema);

// throws error
const validEmail = Joi.attempt('john@doe', schema);

More on Joi here: https://joi.dev/api/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.