使用 express-validator 时的电子邮件验证问题

问题描述

我遵循了全栈课程的步骤。这个问题与 express-validator 依赖有关。我配置并粘贴了传递给我的代码。而postman在sigup url中发送时,出现如下错误信息:

{
         "error": "Email must contain @"
}

但这不应该发生,因为我在电子邮件中插入了@

{
"name": "dave","email": "dave@gmail.com","password": "rrrrrr9"
}

以下是我的应用程序的信息和代码

Express-validator 版本:^ 5.3.1

app.js 文件

const expressValidator = require ('express-validator')

app.use (expressValidator ())

validator/index.js 文件

exports.userSignupValidator = (req,res,next) => {
  req.check ('name','Name is required'). notEmpty ()
  req.check ('name','Email must be between 3 to 32 characters')
     .matches (/.+\@.+\..+/)
     .withMessage ('Email must contain @')
     .isLength ({
       min: 4,max: 32
     })
     req.check ('password','Password is required'). notEmpty ()
     req.check ('password')
     .isLength ({min: 6})
     .withMessage ('Password must contain at least 6 characters')
     .matches (/ \ d /)
     .withMessage ("Password must contain a number")
       const errors = req.validationErrors ()
       if (errors) {
         const firstError = errors.map (error => error.msg) [0]
         return res.status (400) .json ({error: firstError})
       }
       next ()
}

routes/user.js 文件

const express = require('express')
const router = express.Router()

const {userSignupValidator} = require('../validator')
router.post("/signup",userSignupValidator,signup)


module.exports = router

我该如何解决

解决方法

尝试使用这个:-

     [
    check("name","Name is required").not().isEmpty(),check("email","Please enter valid email").isEmail(),check(
      "password","Please enter valid password with 6 or more characters"
    ).isLength({ min: 6 }),],async (req,res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }