Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • PDF Invoice Generator
Menu

Node.js Express Project to Validate User Form Data Using joi Schema Validation Library Full Example

Posted on March 14, 2023

 

 

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

 

 

JavaScript
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

 

 

JavaScript
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 value
  • string(): allows a string value
  • number(): allows a numeric value
  • boolean(): allows a boolean value
  • date(): allows a valid date value
  • array(): allows an array value
  • object(): allows an object value
  • alternatives(): allows a choice of different validation options
  • valid(): allows specific values
  • equal(): allows a value equal to a given value
  • required(): specifies that a value is required
  • optional(): specifies that a value is optional
  • allow(): allows a specific value or values
  • forbidden(): specifies that a value is not allowed
  • empty(): allows an empty value
  • min(): specifies a minimum value
  • max(): specifies a maximum value
  • length(): specifies a length constraint for a value
  • email(): allows a valid email address
  • uri(): allows a valid URI
  • guid(): allows a valid GUID
  • alphanum(): allows only alphanumeric characters
  • regex(): allows a value that matches a regular expression
  • pattern(): allows a value that matches a specific pattern
  • positive(): allows only positive numeric values
  • negative(): allows only negative numeric values

 

 

Recent Posts

  • Node.js Express Project to Remove Background of Images Using Rembg & Formidable Library in Browser
  • Node.js Tutorial to Remove Background From Image Using Rembg & Sharp Library in Command Line
  • Python 3 Flask Project to Remove Background of Multiple Images Using Rembg Library in Browser
  • Python 3 Rembg Library Script to Bulk Process Multiple Images and Remove Background in Command Line
  • Python 3 Rembg Library Script to Remove Background From Image in Command Line
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme