📌  相关文章
📜  如何使用 express-validator 验证输入字段中的输入是否完全等于其他值?

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

如何使用 express-validator 验证输入字段中的输入是否完全等于其他值?

在 HTML 表单中,我们经常需要验证不同的类型。验证现有电子邮件,验证密码长度,验证确认密码,验证仅允许整数输入,这些是验证的一些示例。在某些情况下,我们希望用户键入一些准确的值,并基于此我们授予用户对请求的访问权限或拒绝请求访问。我们还可以验证这些输入字段以接受一些确切的必需值,否则使用 express-validator 中间件拒绝请求。

安装 express-validator 的命令:

npm install express-validator

使用 express-validator 实现逻辑的步骤:

  • 安装 express-validator 中间件。
  • 创建一个validator.js 文件来编码所有的验证逻辑。
  • 通过 validateInputField: check(input field name) 验证输入并使用 ' 链接验证 equals() 。 '
  • 我们还可以使用自定义验证器来验证是否要传递所需的文本以在输入字段中键入作为请求正文。
  • 使用路由中的验证名称(validateInputField)作为验证数组的中间件。
  • 从 express-validator 中解构 'validationResult'函数以使用它来查找任何错误。
  • 如果发生错误,则重定向到传递错误信息的同一页面。
  • 如果错误列表为空,则授予用户后续请求的访问权限。

注意:这里我们使用本地或自定义数据库来实现逻辑,可以按照相同的步骤在MongoDB或MySql等常规数据库中实现逻辑。

示例:此示例说明如何验证输入字段以仅允许某些精确值。

文件名 - index.js

javascript
const express = require('express')
const bodyParser = require('body-parser')
const {validationResult} = require('express-validator')
const repo = require('./repository')
const { validateDeclaration } = require('./validator')
const showTemplet = require('./show')
 
const app = express()
const port = process.env.PORT || 3000
 
// The body-parser middleware to parse form data
app.use(bodyParser.urlencoded({extended : true}))
 
// Get route to display HTML form to type declaration
// and submit to delete the record
app.get('/', (req, res) => {
  res.send(showTemplet({}))
})
 
// Post route to handle form submission logic and
app.post(
  '/record/delete/:id',
  [validateDeclaration],
  async (req, res) => {
    const errors = validationResult(req)
    if(!errors.isEmpty()){
      return res.send(showTemplet({errors}))
    }
    const id = req.params.id
    await repo.delete(id)
    res.send('Record Deleted successfully')
})
 
// Server setup
app.listen(port, () => {
  console.log(`Server start on port ${port}`)
})


javascript
// Importing node.js file system module
const fs = require('fs')
 
class Repository {
  constructor(filename) {
     
    // Filename where datas are going to store
    if(!filename){
      throw new Error('Filename is required to create a datastore!')
    }
 
    this.filename = filename
 
    try {
      fs.accessSync(this.filename)
    } catch(err) {
      // If file not exist it is created with empty array
      fs.writeFileSync(this.filename, '[]')
    }
  }
 
  // Get all existing records
  async getAll(){
    return JSON.parse(
      await fs.promises.readFile(this.filename, {
        encoding : 'utf8'
      })
    )
  }
 
  // Delete record
  async delete(id) {
    const records = await this.getAll()
    const filteredRecords = records.filter(record => record.id !== id)
    await fs.promises.writeFile(
      this.filename,
      JSON.stringify(filteredRecords, null, 2)  
    )
  }
}
 
// The 'datastore.json' file created at runtime
// and all the information provided via signup form
// store in this file in JSON format.
module.exports = new Repository('datastore.json')


javascript
const getError = (errors, prop) => {
  try {
    return errors.mapped()[prop].msg
  } catch (error) {
    return ''
  }
}
 
module.exports = ({errors}) => {
  const id = 'd8f98678eb8a'
  const declaration=
`I read all FAQ and wants to delete the record with id ${id}`
  return `
    
    
      
        
        
      
      
        
          
            
              
Declaration :
              

                ${declaration}               

              
                             
                                                        

${getError(errors,                   'typedDeclaration')}

                
                
                                   
              
            
          
        
                ` }


javascript
const {check} = require('express-validator')
const repo = require('./repository')
module.exports = {
   
  validateDeclaration : check('typedDeclaration')
 
    // To delete leading and trailing space
    .trim()
 
    // Custom validator
    // Check string matches with comparision
    // (some exact value) or not
    .custom(async (typedDeclaration, {req}) => {
      const declaration = req.body.declaration
      if( typedDeclaration !== declaration){
        throw new Error('Please type exact declaration')
      }
    })
}


文件名——repository.js:该文件包含创建本地数据库并与之交互的所有逻辑。

javascript

// Importing node.js file system module
const fs = require('fs')
 
class Repository {
  constructor(filename) {
     
    // Filename where datas are going to store
    if(!filename){
      throw new Error('Filename is required to create a datastore!')
    }
 
    this.filename = filename
 
    try {
      fs.accessSync(this.filename)
    } catch(err) {
      // If file not exist it is created with empty array
      fs.writeFileSync(this.filename, '[]')
    }
  }
 
  // Get all existing records
  async getAll(){
    return JSON.parse(
      await fs.promises.readFile(this.filename, {
        encoding : 'utf8'
      })
    )
  }
 
  // Delete record
  async delete(id) {
    const records = await this.getAll()
    const filteredRecords = records.filter(record => record.id !== id)
    await fs.promises.writeFile(
      this.filename,
      JSON.stringify(filteredRecords, null, 2)  
    )
  }
}
 
// The 'datastore.json' file created at runtime
// and all the information provided via signup form
// store in this file in JSON format.
module.exports = new Repository('datastore.json')

文件名 - show.js:此文件包含显示声明和输入字段类型声明的逻辑。

javascript

const getError = (errors, prop) => {
  try {
    return errors.mapped()[prop].msg
  } catch (error) {
    return ''
  }
}
 
module.exports = ({errors}) => {
  const id = 'd8f98678eb8a'
  const declaration=
`I read all FAQ and wants to delete the record with id ${id}`
  return `
    
    
      
        
        
      
      
        
          
            
              
Declaration :
              

                ${declaration}               

              
                             
                                                        

${getError(errors,                   'typedDeclaration')}

                
                
                                   
              
            
          
        
                ` }

文件名 - validator.js:此文件包含所有验证逻辑(验证输入字段以仅允许某些精确值的逻辑)。

javascript

const {check} = require('express-validator')
const repo = require('./repository')
module.exports = {
   
  validateDeclaration : check('typedDeclaration')
 
    // To delete leading and trailing space
    .trim()
 
    // Custom validator
    // Check string matches with comparision
    // (some exact value) or not
    .custom(async (typedDeclaration, {req}) => {
      const declaration = req.body.declaration
      if( typedDeclaration !== declaration){
        throw new Error('Please type exact declaration')
      }
    })
}

文件名 - package.json

包.json 文件

数据库:

数据库

输出:

当输入不完全等于声明时尝试提交表单

当输入不完全等于声明时尝试提交表单时的响应

当输入与声明完全相等时尝试提交表单

当输入完全等于声明时尝试提交表单时的响应

表单提交成功后的数据库:

表单提交成功后的数据库

注意:我们在 signup.js 文件中使用了一些 Bulma 类(CSS 框架)来设计内容。