Express-validator .isEmail validator not working

Viewed 1171

I'm having a problem with validation. All of it is working except for .isEmail. Even for a valid email address it keeps saying that it's invalid. The .isEmail issue won't go away no matter how I change the validation. I'm using the most up to date version of express-validator.

var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
const { check, validationResult } = require('express-validator');
var validator = require('validator');
var db = mongojs('registerapp', ['users']);
var bcrypt = require('bcryptjs');
var passport = require('passport'); //this could be used to incoporate facebook or twitter password 
for 
example
var LocalStrategy = require('passport-local').Strategy;

// Login Page - GET
router.get('/login', function(req, res) {
res.render('login');
});

// Register Page - GET
router.get('/register', function(req, res) {
res.render('register');
});

//adding the user POST
router.post('/register', [


/**/validation
check('name').notEmpty(),
check('email', 'Your email is required')
.isEmpty()
.isEmail().withMessage('Invalid email address') //The .isEmail issue won't go away no matter how I change the validation
.normalizeEmail(),
check('username').notEmpty(),
check('password', 'invalid password')
.isLength({ min: 1 })
.custom((value, { req, loc, path }) => {
    if (value !== req.body.password2) {
        // throw error if passwords do not match
        throw new Error("Passwords don't match");
    } else {
        return value;
    }
})**

], (req, res, next) => {
//check for errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
    return res.status(422).json({ errors: errors.array() })
} else {
    console.log('success')
}

//Get form values
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password = req.body.password2;
})

module.exports = router;
1 Answers

I had the same problem and I solved it by using directly names of input fields from html form, not the names of variables for these inputs that I created in js files. I see you using 'email' which seem to be correct, but maybe you have a different name for this one in html.

Incorrect code: check('firstname').notEmpty();

Correct code: check('name').notEmpty();, considering that I have in html:

<label for="name">Name</label> <input type="text" id="name" name="name" />

Related