check('username').isEmail(),
check('password').isLength({ min: 5 });
// ...rest of the initial code omitted for simplicity.
const { check, validationResult } = require('express-validator/check');
app.post('/user', [
// username must be an email
check('username').isEmail(),
// password must be at least 5 chars long
check('password').isLength({ min: 5 })
], (req, res) => {
// Finds the validation errors in this request and wraps them in an object with handy functions
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
User.create({
username: req.body.username,
password: req.body.password
}).then(user => res.json(user));
});
{
"errors": [{
"location": "body",
"msg": "Invalid value",
"param": "username"
}]
}
res.render('home', {errors: errors.array()});
{{# if errors }}
{{# each errors }}
<p class="alert alert-danger">{{ this.msg }}</p>
{{/each}}
{{/if}}
app.post('/user', [
// username must be an email
check('username').isEmail(),
// password must be at least 5 chars long
check('password').isLength({ min: 5 })
], (req, res) => {
// Finds the validation errors in this request and wraps them in an object with handy functions
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
// Dependencies
const express = require('express');
const bodyParser = require('body-parser')
const hbs = require('express-hbs');
const { check, validationResult } = require('express-validator/check');
// Main Appliction
const app = express();
// Begin Body Parser Settings
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
// end Body Parser Settings
// begin Set Engine
app.engine('hbs', hbs.express4({
partialsDir: __dirname + '/'
}));
app.set('view engine', 'hbs');
app.set('views', __dirname + '/');
// end Set Engine
// Main route
app.get('/', (req, res) => res.render('index'))
// Login route
app.post('/user', [
// Form Validation
check('username').isEmail(),
check('password').isLength({ min: 5 })
], (req, res) => {
// Const with errors
const errors = validationResult(req);
// Show Errors in console
console.log(errors.array());
// Check for error
if (!errors.isEmpty()) {
// Render template with errors
return res.render('index', {
errors: errors.array()
})
} else {
// Render template without errors
return res.render('index', {
success: 'Success'
})
}
})
// Listener
app.listen(3000, () => console.log('Example app listening on port 3000!'))
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
{{# if errors }}
{{# each errors }}
<p>{{ this.msg }}</p>
{{/each}}
{{/if}}
{{# if success }}
<p>{{ success }}</p>
{{/if}}
<form method="POST" action="/user">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Submit">
</form>
</body>
</html>