Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Node.js Express Server Side Form Validation With Custom Error Messages Using express-validator Library in Javascript

Posted on March 15, 2023

 

Welcome folks today in this blog post we will be implementing server side form validation with custom error messages using express-validator library 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 express-validator

 

 

And after that you need to make an 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
const express = require('express');
const { body, validationResult } = require('express-validator');
 
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(3000, () => {
console.log('Server started on port 3000');
});

 

 

As you can see we are importing the express and express-validator libraries and then we are making a simple route to the / endpoint where we are loading the index.html template when user goes to the home page

 

Now we need to make the index.html inside the public folder as shown below

 

 

public/index.html

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!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>Express-Validator Example</title>
</head>
<body>
    <form>
        <input type="text" name="name" placeholder="Enter name">
        <input type="email" name="email" placeholder="Enter email">
        <input type="submit" value="Register">
    </form>
    <div class="error-messages">
 
    </div>
    <div id="success">
 
    </div>
</body>
</html>

 

 

As you can see we have a simple html5 user form where we have two fields for the user to enter the name and the email and then we have the submit button. And then we have the two div elements where we will be showing the error and success messages for the form validation.

 

 

AJAX Code to Make Fetch Request

 

 

Now guys we will be writing the client side ajax code to make a simple fetch call to the backend api to pass the user data to validate it and show the messages returned as shown below

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<script>
    const form = document.querySelector('form');
    const errorMessages = document.querySelector('.error-messages');
 
    form.addEventListener('submit', event => {
        event.preventDefault();
 
        errorMessages.innerHTML = ''
        document.getElementById('success').innerHTML = ''
 
        const formData = new FormData(form);
 
        fetch('/submit', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                name: formData.get('name'),
                email:formData.get('email')
            })
        })
            .then(response => response.json())
            .then(data => {
                if (data.errors) {
                    errorMessages.innerHTML = '';
                    data.errors.forEach(error => {
                        const li = document.createElement('li');
                        li.textContent = error.msg;
                        errorMessages.appendChild(li);
                    });
                } else {
                    // Handle successful form submission
                    document.getElementById('success').innerHTML = data.msg
                }
            })
            .catch(error => {
                console.error(error);
            });
    });
</script>

 

 

As you can see we are using the fetch call which is built in inside the browser and we are using the formData object to get the name and the email and also we are passing the headers which is for json. And then we are showing the custom error messages returned from the backend.

 

 

Now we need to write the /submit endpoint where we will be submitting the user data to validate and show error messages as shown below

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
app.post('/submit', [
body('name')
        .trim()
        .notEmpty()
        .withMessage("Please enter the name")
.isLength({ min: 2, max: 10 })
    .withMessage('Name must be between 2 and 10 characters')
.isAlpha()
.withMessage('Name must only contain letters'),
    body('email')
        .trim()
        .notEmpty()
        .withMessage("Please enter the email")
        .isEmail()
        .withMessage("Please provide a valid email")
], (req, res) => {
    console.log(req.body.name)
const errors = validationResult(req);
 
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
 
    res.status(200).json({msg:"form is validated"})
});

 

 

As you can see we are passing the express-validator as middleware to the request coming and then we are applying different validators to the name and email alongside with showing custom error messages for each validator. And lastly we can send these error messages as json response back to the client as shown below

 

 

Recent Posts

  • Node.js Express Server Side Form Validation With Custom Error Messages Using express-validator Library in Javascript
  • Node.js Express Project to Validate User Form Data Using joi Schema Validation Library Full Example
  • Node.js Puppeteer Project to Export Handlebars Resume Template to PDF Document in Express Using Javascript
  • Node.js Express Passwordless Login Example to Send Magic Auth Link Using Nodemailer
  • Python 3 Tkinter Script to Encrypt PDF Documents With Password Using PyPDF2 Library GUI Desktop App
  • 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