Published at: 2020-09-17 16:00:00
Updated at: 2023-10-01 13:59:37
There's a lot of validation package you can use for server-side validation. For this particular example, I'm gonna use @hapi/joi validation package with NodeJS back-end environment. It's very simple to implement. I bet you'll be able to use it very easy and quickly.
The only validation package you need to install is @hapi/joi
. Just run npm install @hapi/joi
and you are ready to get to the next step.
Normally, we would use this validation for form input submission. So, that will be the example I'll give show to you.
Let's say we have a page register.ejs
(assuming that you are using ejs
for front-end javascript templating) like so:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Register</title>
</head>
<body>
<div>
<h2>REGISTER PAGE</h2>
<p>Insert your credentials below:-</p>
<form action="/register" method="POST">
<!-- Display error message -->
<% if(message !== null) { %>
<div class="error">
<p class="message"><%= message %> </p>
<p class="close" id="close">X</p>
</div>
<% } %>
<!-- User's Email -->
<input type="email" name="email" placeholder="Email" required>
<div>
<!-- User's Password -->
<input type="password" name="password" placeholder="Password" required>
<!-- User's Password Confirm -->
<input type="password" name="passwordConfirm" placeholder="Re-type Password" required>
</div>
<div>
<!-- User's Firstname -->
<input type="text" name="firstName" placeholder="Firstname" required>
<!-- User's Lastname -->
<input type="text" name="lastName" placeholder="Lastname" required>
</div>
<button type="submit">Register</button>
</form>
</div>
<!-- Custom Script -->
<script>
// handle closing of error warning/alert
document.querySelector('.form').addEventListener('click', event => {
// get id of div close
let closeID = event.target.id
// if target id === close, then
if(closeID === 'close') {
// remove the warning/alert
document.querySelector('.error').style.display = 'none'
}
})
</script>
</body>
</html>
So of course we also will have two routes to handle get
& post
from & to the back-end of the system, like so:-
// import validation file
const { registerValidation } = require('./controllers/validations')
// REGISTER Get Router
app.get('/register', (req, res) =>
// 1. render Register page
res.render('register', { message: null })
})
// REGISTER Post Router
app.post('/register', (req, res) =>
let { email, password, passwordConfirm, firstName, lastName } = req.body
// 1. do validation
const { error } = registerValidation(req.body)
if(error) return res.render('register', { message: error.details[0].message })
// 2. check email already exist in DB
// 3. hash password with bcryptjs
// 4. save new user to DB
// 5. redirect new user to Login page
})
This is where you validation happen:-
projectFolder/controllers/validations.js
:-/** Import Dependencies */
// Joi
const joi = require('@hapi/joi')
/** Validation Schema */
// REGISTER Validation Schema
const registerValidation = data => {
const schema = joi.object({
email: joi
.string() // type of input
.min(6) // min amount of input allowed
.required() // cannot be left empty
.email(), // should be type/syntax of email
password: joi
.string() // type of input
.min(6) // min amount of input allowed
.max(72, 'utf8') // max amount of input allowed
.required(), // cannot be left empty
passwordConfirm: joi
.valid(joi.ref('password')) // should be exactly the same like 'password' above
.required(), // cannot be left empty
firstName: joi
.string() // type of input
.min(4) // min amount of input allowed
.required(), // cannot be left empty
lastName: joi
.string() // type of input
.min(4) // min amount of input allowed
.required() // cannot be left empty
})
// validate the schema
return schema.validate(data)
}
/** Validation Schema Exports */
module.exports = { registerValidation }
The codes and comments given are self explanatory. It's easy to use and implement. If you wanna see or code together with me, then you can go to this link, Server-side Validation in NodeJS - Hapi Joi.
Anyway, that's all for today. Like always, until next time, Chao! Salam.