Create a code for form validation using java script in node js.

Here, we will write a program to validate a java form in node js. For that we need to create two files, one will be app.js which will contain our imported libraries and schemas and another will be index.js file where we will design our form to validate.

app.js

const express=require('express');
const fastestValidator=require('fastest-validator');
var bodyParser=require('body-parser');
const expressSession=require('express-session');
const v = new fastestValidator();
const app=express();

app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json())
app.use(expressSession({
    secret:"Itsasecretkey",
    saveUninitialized:false, 
    resave:false
 }))

app.set("view engine","ejs")
app.get('/',(req,res)=>{
    res.render("index",{usernameerror:req.session.usernameerror,emailerror:req.session.emailerror,passworderror:req.session.passworderror,
    success:req.session.success});
    req.session.usernameerror=null;
    req.session.emailerror=null;
    req.session.passworderror=null;
    req.session.success=null;
})

const schema = {
    username : {
        type:"string",min:5,max:15
    },
    email:{
        type:"email"
    },
    password:{
        type:"string", min:4
    }
}

app.post('/',(req,res)=>{
    var username=req.body.username;
    var email=req.body.email;
    var password=req.body.password;

    const check = v.compile(schema);
    const result=check({
        username:username,
        email:email,
        password:password
    })
    if(result){
        req.session.success=true;
        res.redirect('/')
    }
    else{
        req.session.usernameerror=result[0].message;
        req.session.emailerror=result[1].message;
        req.session.passworderror=result[2].message;
        req.session.success=false;
        res.redirect('/')
    }

    console.log(username);
    console.log(email);
    console.log(password);
    console.log(result);
})
app.listen(4000,()=>{
    console.log("App is listening on port 4000")
})

index.js

<!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 Validation using javascript</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
    <div class="container"><br>
        <h1 class="text-center">Form Validation using Express in Node js.</h1><br>
        <% if(success) { %>
            <div>
               <p class="alert alert-success"> Form Successfully Validated </p>
            </div>
        <% } %>
        <form action="/" method="post" autocomplete="off">
            <% if(usernameerror) { %>
                <p class="alert alert-danger"><%= usernameerror %></p>
                <% } %>
            <div class="form-group">
              <input type="text" placeholder="username" name="username" class="form-control">
            </div><br>
            <% if(emailerror) { %>
                <p class="alert alert-danger"><%= emailerror %></p>
                <% } %>
            <div class="form-group">
              <input type="text" name="email" id="" placeholder="Email" class="form-control">
            </div><br>
            <% if(passworderror) { %>
                <p class="alert alert-danger"><%= passworderror %></p>
                <% } %>
            <div class="form-group">
                <input type="password" name="password" id="" placeholder="Password" class="form-control">
            </div><br>
            <div class="form-group" class="form-control" >
                <button class="btn btn-danger btn-block">
                    Submit
                </button>
            </div>
        </form>
    </div>
    
</body>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

</html>