Karl Bateman Karl Bateman - 6 months ago 23
Node.js Question

NodeJS returns invalid for valid email address regex

EDIT NodeJS route handler

// require() statements above
let error = {};

module.exports = {
authorize: (req, res, next) => {
const USERNAME = req.body.username,
PASSWORD = req.body.password,
SCOPES = req.body.scopes;

console.log(req.body);

const SCOPE_LOOKUP = ['read', 'write', 'admin'];
if(!VALIDATE_EMAIL(USERNAME)) {
error.message = 'Invalid username.';
}

if(error.message) { return next(error) };
return res.status(200).json(req.body);
}
};


The code below runs on a NodeJS application I am working on. The email address
const
is populated with the contents of
req.body.email
and I am using Postman to make the API calls.

Running the code below and passing a valid email address will work as expected. However if I pass an invalid email address the code also works as expected, but when I pass in another valid email address I end up with
Invalid email
. This occurs with no restart of the server.

Is there an issue with execution order or scope, which I have missed?



const VALIDATE_EMAIL = email => {
const EXP = /^(([^<>()[\]\\.,;:\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,}))$/;
const DOMAIN = '@example.com';
const OUTPUT = (EXP.test(email) && email.indexOf(DOMAIN, email.length - DOMAIN.length) !== -1) ? true : false;
return OUTPUT;
};
(() => {
let error = {};
const EMAIL = 'joebloggs@example.com';

if(!VALIDATE_EMAIL(EMAIL)) {
error.message = 'Invalid email.';
}

if(error.message) { console.log(error.message); return };
console.log(EMAIL);
})();




Answer

Your problem is that you're persisting your error message throughout the lifecycle of your application. Don't declare the error object outside the scope of the handler... You need to declare the error object within the request handler so that each request has a fresh error object (and subsequent error message).

module.exports = {
  authorize: (req, res, next) => {
    const error = {
      message: '',
      something: '',
      foo: ''
    };

    const USERNAME  = req.body.username,
          PASSWORD  = req.body.password,
          SCOPES    = req.body.scopes;

    console.log(req.body);

    const SCOPE_LOOKUP = ['read', 'write', 'admin'];
    if(!VALIDATE_EMAIL(USERNAME)) {
      error.message = 'Invalid username.';
    }

    if(error.message) { return next(error) };
    return res.status(200).json(req.body);
  }
};
Comments