📌  相关文章
📜  如何在 Node.js 中使用 express-validator 模块验证数据?

📅  最后修改于: 2022-05-13 01:56:28.222000             🧑  作者: Mango

如何在 Node.js 中使用 express-validator 模块验证数据?

使用 express-validator 模块可以轻松完成 node.js 中的验证。该模块在数据验证方面很受欢迎。市场上还有其他可用的模块,如 hapi/joi 等,但 express-validator 被广泛使用并在其中流行。
安装 express-validator 模块的步骤:

  1. 您可以使用此命令安装此软件包。
npm install express-validator
  1. 安装后,您可以使用命令在命令提示符下检查您的 express-validator 模块版本。
npm version express-validator
  1. 之后,您只需创建一个如下所示的简单数据即可将数据发送到服务器。
    文件名:SampleForm.ejs
html


    
        Validation using Express-Validator
    

Demo Form

  
  
      Enter your Email    :  
      Enter your Name     :
      Enter your Number   :
      Enter your Password :
         
  


javascript
const { check, validationResult }
    = require('express-validator');
 
const bodyparser = require('body-parser')
const express = require("express")
const path = require('path')
const app = express()
 
var PORT = process.env.port || 3000
 
// View Engine Setup
app.set("views", path.join(__dirname))
app.set("view engine", "ejs")
 
// Body-parser middleware
app.use(bodyparser.urlencoded({ extended: false }))
app.use(bodyparser.json())
 
app.get("/", function (req, res) {
    res.render("SampleForm");
})
 
// check() is a middleware used to validate
// the incoming data as per the fields
app.post('/saveData', [
    check('email', 'Email length should be 10 to 30 characters')
                    .isEmail().isLength({ min: 10, max: 30 }),
    check('name', 'Name length should be 10 to 20 characters')
                    .isLength({ min: 10, max: 20 }),
    check('mobile', 'Mobile number should contains 10 digits')
                    .isLength({ min: 10, max: 10 }),
    check('password', 'Password length should be 8 to 10 characters')
                    .isLength({ min: 8, max: 10 })
], (req, res) => {
 
    // validationResult function checks whether
    // any occurs or not and return an object
    const errors = validationResult(req);
 
    // If some error occurs, then this
    // block of code will run
    if (!errors.isEmpty()) {
        res.json(errors)
    }
 
    // If no error occurs, then this
    // block of code will run
    else {
        res.send("Successfully validated")
    }
});
 
app.listen(PORT, function (error) {
    if (error) throw error
    console.log("Server created Successfully on PORT ", PORT)
})


  1. 之后,您可以创建一个文件,例如 index.js,如下所示:
    文件名:index.js

javascript

const { check, validationResult }
    = require('express-validator');
 
const bodyparser = require('body-parser')
const express = require("express")
const path = require('path')
const app = express()
 
var PORT = process.env.port || 3000
 
// View Engine Setup
app.set("views", path.join(__dirname))
app.set("view engine", "ejs")
 
// Body-parser middleware
app.use(bodyparser.urlencoded({ extended: false }))
app.use(bodyparser.json())
 
app.get("/", function (req, res) {
    res.render("SampleForm");
})
 
// check() is a middleware used to validate
// the incoming data as per the fields
app.post('/saveData', [
    check('email', 'Email length should be 10 to 30 characters')
                    .isEmail().isLength({ min: 10, max: 30 }),
    check('name', 'Name length should be 10 to 20 characters')
                    .isLength({ min: 10, max: 20 }),
    check('mobile', 'Mobile number should contains 10 digits')
                    .isLength({ min: 10, max: 10 }),
    check('password', 'Password length should be 8 to 10 characters')
                    .isLength({ min: 8, max: 10 })
], (req, res) => {
 
    // validationResult function checks whether
    // any occurs or not and return an object
    const errors = validationResult(req);
 
    // If some error occurs, then this
    // block of code will run
    if (!errors.isEmpty()) {
        res.json(errors)
    }
 
    // If no error occurs, then this
    // block of code will run
    else {
        res.send("Successfully validated")
    }
});
 
app.listen(PORT, function (error) {
    if (error) throw error
    console.log("Server created Successfully on PORT ", PORT)
})

运行程序的步骤:

  1. 项目结构如下图所示:

项目结构

  1. 确保你有一个“视图引擎”。我们使用了“ejs”,还使用以下命令安装了 express 和 express-validator、body-parser:
npm install ejs
npm install express
npm install body-parser
npm install express-validator
  1. 使用以下命令运行 index.js 文件:
node index.js

节点 index.js 的输出

  1. 打开浏览器并输入此 URL http://localhost:8080/ ,使用正确的数据填写此示例表单,如下所示:

注册.ejs

  1. 然后提交表单,如果没有错误发生,那么您将看到以下输出:

成功输出

  1. 如果您尝试使用不正确的数据提交表单,那么您将看到如下所示的错误消息:

错误信息