如何验证输入字段中的输入是否仅使用 express-validator 有字母?
在 HTML 表单中,我们经常需要验证不同的类型。验证现有电子邮件、验证密码长度、验证确认密码、验证以仅允许整数输入,这些是验证的一些示例。在某个输入字段中,只允许使用字母,即不允许任何数字或特殊字符。我们还可以使用 express-validator 中间件验证这些输入字段以仅接受字母。
安装 express-validator 的命令:
npm install express-validator
使用 express-validator 实现逻辑的步骤:
- 安装 express-validator 中间件。
- 创建一个validator.js 文件来编码所有的验证逻辑。
- 通过 validateInputField: check(input field name) 验证输入并在验证 isAlpha() 上使用 ' 链接。 '
- 使用路由中的验证名称(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 { validateFirstName, validateLastName } = 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 up
app.get('/signup', (req, res) => {
res.send(signupTemplet({}))
})
// Post route to handle form submission logic and
app.post(
'/signup',
[validateFirstName, validateLastName],
async (req, res) => {
const errors = validationResult(req)
if(!errors.isEmpty()){
return res.send(signupTemplet({errors}))
}
const {email, fn, ln, password} = req.body
await repo.create({
email,
'First Name':fn,
'Last Name': ln,
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'
})
)
}
// 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
`
}
javascript
const {check} = require('express-validator')
const repo = require('./repository')
module.exports = {
validateFirstName : check('fn')
// To delete leading and trailing space
.trim()
// Validate the minimum length of the password
// Optional for this context
.isLength({min:3})
// Custom message
.withMessage('First Name must be 3 characters long')
// Name must contains only alphabets
.isAlpha()
// Custom message
.withMessage('First Name must be alphabetic'),
validateLastName : check('ln')
// To delete leading and trailing space
.trim()
// Validate the minimum length of the password
// Optional for this context
.isLength({min:2})
// Custom message
.withMessage('Last Name must be 2 characters long')
// Name must contains only alphabets
.isAlpha()
// Custom message
.withMessage('Last Name must be alphabetic')
}
文件名——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'
})
)
}
// 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
`
}
文件名 - validator.js:此文件包含所有验证逻辑(验证输入字段以仅允许字母的逻辑)。
javascript
const {check} = require('express-validator')
const repo = require('./repository')
module.exports = {
validateFirstName : check('fn')
// To delete leading and trailing space
.trim()
// Validate the minimum length of the password
// Optional for this context
.isLength({min:3})
// Custom message
.withMessage('First Name must be 3 characters long')
// Name must contains only alphabets
.isAlpha()
// Custom message
.withMessage('First Name must be alphabetic'),
validateLastName : check('ln')
// To delete leading and trailing space
.trim()
// Validate the minimum length of the password
// Optional for this context
.isLength({min:2})
// Custom message
.withMessage('Last Name must be 2 characters long')
// Name must contains only alphabets
.isAlpha()
// Custom message
.withMessage('Last Name must be alphabetic')
}
文件名 - package.json
输出:
注册成功后的数据库:
注意:我们在 signup.js 文件中使用了一些 Bulma 类(CSS 框架)来设计内容。