13 October 2019

NodeJS ExpressJS: Server-side validation [EX-12]

Server-side validation

/views/users/create.pug
create.pug
extends ../layouts/common.pug 

block content
    div(class="container col-3")
        h3(class="text-uppercase text-center alert alert-danger mt-3") Create user
        
        if errors
            each error in errors
                .alert.alert-danger=  error

        form(action="/users/create", method="POST")
            label Name
            div(class="input-group mb-3")
                input(name="name", type="text", autocomplete="off" class="form-control" placeholder="Enter name")
                div(class="input-group-append")
                    button(class="btn btn-success") create
        a(href="/users") << back

/controller/user.controller.js
user.controller.js
const db = require('../db/index').lowDB;
var ids = require('short-id');

module.exports.index = function (req, res) {
    res.render('users/index', {
        users: db.get('users').value()
    })
}

module.exports.create = function (req, res) {
    res.render('users/create')
}

module.exports.postCreate = function (req, res) {
    // Add a post
    var errors = [];
    if (!req.body.name) {
        errors.push('Name is required.');
    }
    if (errors.length) {
        res.render('users/create', {
            errors: errors
        })
        return;
    }
    req.body.id = ids.generate();
    db.get('users').push(req.body).write()
    res.redirect('/users');
}

module.exports.get = function (req, res) {
    var id = req.params.id;
    res.render('users/view', {
        user: db.get('users').find({
            id: id
        }).value()
    })
}

module.exports.search = function (req, res) {
    var q = req.query.name;
    var matchUsers = db.get('users').value().filter(f => f.name.toLocaleLowerCase().indexOf(q.toLocaleLowerCase()) !== -1);
    res.render('users/index', {
        users: matchUsers
    })
}

Command: npm start

<< back | next >>

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang