Search code examples
node.jsexpressexpress-validator

Using express-validator to check if input is a username or email


I am trying to validate a login request where it accepts a username that can either be a email or username, and a password. How can I do this with Express-Validator?

I'm reading the documentation and the way the validator works is that you have to pass in the data as the second argument. I'm not sure how that's done with checking to see if it's also a username or password.

router.post("/", (req, res) => {
    const { nickname, password } = req.body;
    // Create a new object based on email or username
    const login = {};
    if (nickname.indexOf('@') === -1) {
        login.nickname = nickname;
    } else {
        login.email = nickname;
    }
    login.password = password;
    // JWT Sign...
});

With the validator, I'd also like to check if it's

  • A username or email
  • If it's a email, make sure it's an actual email using isEmail() validator
  • If it's a username, make sure it's more then three characters and there's an actual username.

Attempt

router.post("/", (req, res) => {
    const { nickname, password } = req.body;
    // Create a new object based on email or username
    const login = {};
    if (nickname.indexOf('@') === -1) {
        check('nickname').isLength({ 'min': 3 });
        login.nickname = nickname;
    } else {
        check('nickname').isEmail();
        login.email = nickname;
    }
    login.password = password;
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(422).json({ errors: errors.array() });
    }
});

Seemed like the validator just didn't work.


Solution

  • try this,

    npm install validator
    

    and

    npm install express-validator
    

    then

    const {check, oneOf } = require('express-validator')
    const validator = require('validator')
    

    in your validation function try this,

    oneOf([
      check('nickname').isEmail(),
      check('nickname').not().isEmpty().isString().custom((value, {req})=>{
         if(!validator.isEmail(value)){
           req.body.flag = true
           // you can handler your req.body here .... 
    
         }
         return true
      })
    ]