Welcome folks today in this blog post we will be implementing form validation
using joi
schema validation library in node.js
and express in javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new node.js
project using the below command as shown below
npm init -y
npm i express
npm i joi
Now you will need to create the index.js
file and copy paste the following code
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
const express = require("express"); const Joi = require("joi"); const app = express(); app.use(express.urlencoded({ extended: false })); app.use(express.json()); app.use(express.static("public")); app.get("/", (req, res) => { res.sendFile("index.html"); }); app.listen(5000, () => { console.log("App is listening on port 5000"); }); |
As you can see we are importing the express
and joi
schema validation library and then we are loading the index.html
file when users goes to the /
endpoint. And now you need to create the public
folder and inside it we need to create the index.html
file and copy paste the following code
public/index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form autocomplete="off" action="/submit" method="post"> <input type="text" name="name"> <input type="text" name="email"> <input type="password" name="password"/> <input type="submit" value="Register"/> </form> </body> </html> |
As you can see we have three input
fields for receiving the name,email
and password
data. And then we are making the post
request to the /submit
endpoint. And now we need to add the code inside the index.js
as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
app.post("/submit", (req, res) => { const schema = Joi.object({ name: Joi.string().required(), email: Joi.string().email().required(), password: Joi.string().max(8).required(), }); const { error } = schema.validate(req.body); if (error) { const errorDetails = error.details.map((d) => d.message).join("<br>"); res.send(`<h2>Validation Error:</h2>${errorDetails}`); return; } res.send("<h2>Form Submitted Successfully</h2>"); }); |
As you can see we are defining the schema
which contains different validators for name
email and password. required() validator makes the field required so that user must fill out that field and then we have the email()
validator which makes sure the email entered is valid one and then min()
validator makes sure the password must be atleast 8
characters and the string()
validator makes sure the entered value is string
Here is a list of some of the most commonly used validations supported by Joi:
any()
: allows any valuestring()
: allows a string valuenumber()
: allows a numeric valueboolean()
: allows a boolean valuedate()
: allows a valid date valuearray()
: allows an array valueobject()
: allows an object valuealternatives()
: allows a choice of different validation optionsvalid()
: allows specific valuesequal()
: allows a value equal to a given valuerequired()
: specifies that a value is requiredoptional()
: specifies that a value is optionalallow()
: allows a specific value or valuesforbidden()
: specifies that a value is not allowedempty()
: allows an empty valuemin()
: specifies a minimum valuemax()
: specifies a maximum valuelength()
: specifies a length constraint for a valueemail()
: allows a valid email addressuri()
: allows a valid URIguid()
: allows a valid GUIDalphanum()
: allows only alphanumeric charactersregex()
: allows a value that matches a regular expressionpattern()
: allows a value that matches a specific patternpositive()
: allows only positive numeric valuesnegative()
: allows only negative numeric values