In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. If In a certain input field only base 64 encoded string are allowed i.e there not allowed any other form of string which not constitute base64 encoded string. We can also validate these input fields to accept only base 64 encoded string using express-validator middleware.
Steps to use express-validator to implement the logic:
- Install express-validator middleware.
- Create a validator.js file to code all the validation logic.
- Validate input by validateInputField: check(input field name) and chain on the validation isBase64() with ‘ . ‘
- Use the validation name(validateInputField) in the routes as a middleware as an array of validations.
- Destructure ‘validationResult’ function from express-validator to use it to find any errors.
- If error occurs redirect to the same page passing the error information.
- If error list is empty, give access to the user for the subsequent request.
Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql.
const express = require('express')
const bodyParser = require('body-parser')
const {validationResult} = require('express-validator')
const repo = require('./repository')
const { validateBase64Data } = require('./validator')
const formTemplet = require('./form')
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
app.get('/', (req, res) => {
res.send(formTemplet({}))
})
// Post route to handle form submission logic and
app.post(
'/data',
[validateBase64Data],
async (req, res) => {
const errors = validationResult(req)
if(!errors.isEmpty()){
return res.send(formTemplet({errors}))
}
const {name, base64data} = req.body
await repo.create({
name,
base64data
})
res.send('<h2>Base 64 data decoded and '
+ 'Stored successfully in the database</h2>')
})
// Server setup
app.listen(port, () => {
console.log(`Server start on port ${port}`)
})