Node.js Form Validation in Express-Validator

 
 
Install 
 npm install express body-parser ejs express-validator

// index.js
var express = require('express');
var Bodyperser = require('body-parser');
var ejs = require('ejs');
var path = require('path');

const { check, validationResult } = require('express-validator/check');
const { matchedData, sanitize } = require('express-validator/filter');

var app = express();

app.set('view engine','ejs');
app.set('views', path.join(__dirname,'views'));

app.use(Bodyperser.json());
app.use(Bodyperser.urlencoded({extended:false}));
app.use(express.static(path.join(__dirname,'public')));

app.listen(3001, function () {
    console.log('Server started on port 3001')
})

app.get('/', function (req, res) {
    res.render('home/index');
});

app.get('/about', function (req, res) {
    res.render('home/about');
});

app.get('/registration', function (req, res) {
    const errors = matchedData(req);
    res.render('home/registration',{errors: errors, user: null});
});

app.post('/registration', [
    check('email').trim().isEmail().normalizeEmail(),
    check('fullname').trim().isLength({min:3}).withMessage('Minimum Full name length 3'),
    check('password').trim().isLength({min:5}).withMessage('Minimum Password length 5'),
    check('repassword').custom((value,{req}) => {
        if(value !== req.body.password){
        throw new Error('Pasword Not matched');

        }
        else {
            return true;
        }
    }).trim().isLength({min:5}).withMessage('Minimum Re-password length 5'),


],function (req, res) {

    const errors = validationResult(req);
    if(!errors.isEmpty()){
        console.log(errors.mapped());
        const user = matchedData(req);
       return res.render('home/registration', {errors: errors.mapped(),user:user});
    }
    else{

        const user = matchedData(req);
        console.log(user);
        res.send(user);

    }

});
//home/registration.ejs 
 
<div class="card">
    <div class="card-header">
        Registration
    </div>
    <div class="card-body">

        <form method="post" action="/registration">
            <div class="form-group">
                <label for="exampleInputEmail1">Email address</label>
                <input type="email" class="form-control <% if (errors.email) { %>is-invalid <% } %>" id="email" value="<% if (user){ %> <%= user.email %> <% } %>" name="email" placeholder="Enter email">
                    <% if (errors.email) { %>
                <div class="invalid-feedback">
                    <%= errors.email.msg %>
                </div>
                <% } %>
            </div>

            <div class="form-group">
                <label for="fullname">Full name</label>
                <input type="text" class="form-control <% if (errors.fullname) { %>is-invalid <% } %>" value="<% if (user){ %> <%= user.fullname %> <% } %>" id="fullname" name="fullname" placeholder="Enter Full name">
                <% if (errors.fullname) { %>
                    <div class="invalid-feedback">
                        <%= errors.fullname.msg %>
                    </div>
                <% } %>
            </div>


            <div class="form-group">
                <label for="password">Password</label>
                <input type="password" class="form-control <% if (errors.password) { %> is-invalid <% } %>" value="<% if (user){ %> <%= user.password %> <% } %>" id="password" name="password" placeholder="Password">
                <% if (errors.password) { %>
                    <div class="invalid-feedback">
                        <%= errors.password.msg %>
                    </div>
                <% } %>
            </div>

            <div class="form-group">
                <label for="repassword">Re-Password</label>
                <input type="password" class="form-control <% if (errors.repassword) { %>is-invalid <% } %>" value="<% if (user){ %> <%= user.repassword %> <% } %>" id="repassword" name="repassword" placeholder="Re-Password">
                <% if (errors.repassword) { %>
                    <div class="invalid-feedback">
                        <%= errors.repassword.msg %>
                    </div>
                <% } %>
            </div>

            <button type="submit" class="btn btn-primary">Registration</button>
        </form>

    </div>
</div> 

Comments

Popular posts from this blog

React Context API (Hooks and Classes)

Express ejs with mongoose pagination

React Filter