Search code examples
node.jsangularvalidationemailexpress

How to format and validate email node js


I would like that email had format like: a@b.c.

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!


Solution

  • 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 = 'a@a.com';
    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.