📜  如何使用 express-validator 比较密码和确认密码输入?

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

如何使用 express-validator 比较密码和确认密码输入?

任何网站的注册或注册都需要输入确认密码,并且必须与密码相同。基本上是为了保证用户输入的密码充满了他的感觉,不会发生冲突。此功能可以在我们的代码中的任何位置实现,例如在索引文件或路由文件中,但这属于验证部分。所以我们通常更喜欢在所有其他验证都被编码的地方编码这个逻辑。这里我们使用“express-validator”中间件来实现这个功能。

安装 express-validator 的命令

npm install express-validator

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

  • 安装 express-validator 中间件。
  • 创建一个validator.js 文件来编码所有的验证逻辑。
  • 通过 validateConfirmPassword: check('confirmPassword') 验证 confirmPassword 并使用 ' 链接所有验证。 '
  • 在路由中使用验证名称(validateConfirmPassword)作为验证数组的中间件。
  • 从 express-validator 中解构 'validationResult'函数以使用它来查找任何错误
  • 如果发生错误重定向到传递错误信息的同一页面
  • 如果错误列表为空,则授予用户后续请求的访问权限。

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

示例 1:此示例说明如何检查特定网站的电子邮件地址是否已在使用中。

文件名:index.js

javascript
const express = require('express')
const bodyParser = require('body-parser')
const {validationResult} = require('express-validator')
const repo = require('./repository')
const { validateConfirmPassword } = require('./validator')
const signupTemplet = require('./signup')
 
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 sign in
app.get('/signup', (req, res) => {
  res.send(signupTemplet({}))
})
 
// Post route to handle form submission logic and
app.post(
  '/signup',
  [validateConfirmPassword],
  async (req, res) => {
    const errors = validationResult(req)
    if(!errors.isEmpty()){
      return res.send(signupTemplet({errors}))
    }
    const {email, password} = req.body
    await repo.create({email, password})
    res.send('Sign Up 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) {
 
        // The 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'
            })
        )
    }
 
    // Find record by properties
    async getOneBy(filters) {
        const records = await this.getAll()
        for (let record of records) {
            let found = true
            for (let key in filters) {
                if (record[key] !== filters[key]) {
                    found = false
                }
            }
            if (found) return record;
        }
    }
 
    // Create new record
    async create(attrs) {
        const records = await this.getAll()
        records.push(attrs)
        await fs.promises.writeFile(
            this.filename,
            JSON.stringify(records, null, 2)
        )
        return attrs
    }
}
 
// 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 }) => {
    return `
      
      
        
          
          
        
    
      
        
          
            

Sign Up

            
                           
                
                                  
                               
              
                
                                   
                               
              
                
                                  
                                 

                    ${getError(errors, 'confirmPassword')}                 

              
              
                               
            
          

        
      
                ` }


javascript
const {check} = require('express-validator')
const repo = require('./repository')
module.exports = {
   
  validateConfirmPassword : check('confirmPassword')
 
    // To delete leading and trailing space
    .trim()
 
    // Validate minimum length of password
    // Optional for this context
    .isLength({min:4, max:16})
 
    // Custom message
    .withMessage('Password must be between 4 to 16 characters')
 
    // Custom validation
    // Validate confirmPassword
    .custom(async (confirmPassword, {req}) => {
      const password = req.body.password
 
      // If password and confirm password not same
      // don't allow to sign up and throw error
      if(password !== confirmPassword){
        throw new Error('Passwords must be same')
      }
    }),
}


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

javascript

// Importing node.js file system module
const fs = require('fs')
 
class Repository {
    constructor(filename) {
 
        // The 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'
            })
        )
    }
 
    // Find record by properties
    async getOneBy(filters) {
        const records = await this.getAll()
        for (let record of records) {
            let found = true
            for (let key in filters) {
                if (record[key] !== filters[key]) {
                    found = false
                }
            }
            if (found) return record;
        }
    }
 
    // Create new record
    async create(attrs) {
        const records = await this.getAll()
        records.push(attrs)
        await fs.promises.writeFile(
            this.filename,
            JSON.stringify(records, null, 2)
        )
        return attrs
    }
}
 
// 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')

文件名:signup.js此文件包含显示注册表单的逻辑。

javascript

const getError = (errors, prop) => {
    try {
        return errors.mapped()[prop].msg
    } catch (error) {
        return ''
    }
}
 
module.exports = ({ errors }) => {
    return `
      
      
        
          
          
        
    
      
        
          
            

Sign Up

            
                           
                
                                  
                               
              
                
                                   
                               
              
                
                                  
                                 

                    ${getError(errors, 'confirmPassword')}                 

              
              
                               
            
          

        
      
                ` }

文件名:validator.js此文件包含所有验证逻辑(逻辑查看密码和密码确认是否相同)。

javascript

const {check} = require('express-validator')
const repo = require('./repository')
module.exports = {
   
  validateConfirmPassword : check('confirmPassword')
 
    // To delete leading and trailing space
    .trim()
 
    // Validate minimum length of password
    // Optional for this context
    .isLength({min:4, max:16})
 
    // Custom message
    .withMessage('Password must be between 4 to 16 characters')
 
    // Custom validation
    // Validate confirmPassword
    .custom(async (confirmPassword, {req}) => {
      const password = req.body.password
 
      // If password and confirm password not same
      // don't allow to sign up and throw error
      if(password !== confirmPassword){
        throw new Error('Passwords must be same')
      }
    }),
}

文件名:package.json

包.json 文件

数据库:

数据库

输出:

当密码和确认密码输入不同时尝试注册

尝试使用不同密码注册并确认密码输入时的响应

当密码和确认密码输入相同时尝试注册

尝试使用相同密码注册并确认密码输入时的响应

注册成功后的数据库(使用相同的密码注册并确认密码输入)

注册成功后的数据库(使用相同的密码注册并确认密码输入)

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