Express request validator with object's style response body and inspired by Laravel's Validator
yarn add cheke
or
npm install --save cheke
- Array:
array - Boolean:
boolean - Date:
date - Email:
email - Integer:
integer - Maximum:
max:maximumNumber - Minimum:
min:minimumNumber - Number:
number,number|min:200,number|max:200 - Regular Expression:
regx:^[a-z]{6,} - Required:
required - String:
string,string|min:200,string|max:200 - UUID:
uuid - Object:
object
- query ->
GET /validate-query?page=pageNumberapp.get('/validate-query', cheke({ query: { pageNumber: 'required|number|min:1', } }),(req, res) => { return res.send({ message: 'Validated' }); });app.get('/validate-query', cheke({ query: { pageNumber: { label: 'Page', type: 'required|number|min:1' }, } }),(req, res) => { return res.send({ message: 'Validated' }); }); - params ->
GET /validate-params/:idapp.get('/validate-params/:id', cheke({ params: { id: 'required|uuid' } }),(req, res) => { return res.send({ message: 'Validated' }); });app.get('/validate-params/:id', cheke({ params: { id: { label: 'ID', type: 'required|uuid' } } }),(req, res) => { return res.send({ message: 'Validated' }); }); - body ->
POST /validate-bodyapp.post('/validate-body', cheke({ body: { username: 'required|string|min:6', password: 'required|string|min:6' } }),(req, res) => { return res.send({ message: 'Validated' }); });app.post('/validate-body', cheke({ body: { username: { label: 'Username', type: 'required|string|min:6' }, password: { label: 'Password', type: 'required|string|min:6' } } }),(req, res) => { return res.send({ message: 'Validated' }); });
const express = require('express');
const cheke = require('cheke);
const app = express();
const { PORT = 3000 } = process.env
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.get('/validate', cheke({
query: {
page: 'required|number'
}
}),(req, res) => {
return res.send({ message: 'Validated' });
});
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use((err, req, res) => {
res.status(err.status || 500).json({
errors: {
message: err.message,
error: err
}
});
});
app.listen(PORT, () => console.log(`Server listen on port ${PORT}...`));
Should it happen that the tool broke down on you please head to our Issue tracker
- Search if the issue is already discussed or explained.
- If no luck feel free to open a new issue and we will get back to you as soon as possible.
- Alpha Ogilo Ogilo
- Grace Njoki Kimotho kimotho-njoki
- Rene Christian Nshogoza filschristian