Comments (4)
With express-validators, isn't it done more like check('something').not().isEmpty()
. I think body('time').exists({checkNull: true})
is checking to see if it is null. I'm not sure though cause I haven't used express-validators before.
from overnight.
Thanks for reply @seanpmaxwell.
I just try your suggestion but again any error is thrown if my body is empty. Now, my controller looks like:
@Controller('vehicle/:vehicle_id/engine')
@ClassOptions({mergeParams: true})
export class VehicleEngineController {
@Post()
@Middleware(check('time').not().isEmpty())
private async insertData(req: Request, res: Response) {
return res.status(200).send(`Receive Data from Vehicle ${req.params.vehicle_id}`);
}
}
However, If I code my own validator function and pass through @Middleware, it works perfectly. I don't know if, maybe, there is any problem with express-validator and annotations.
Thank you.
from overnight.
This isn't related to express-validator
, but I'm using a custom validator like this, in case it helps:
@Controller("users")
export class UserController {
@Put()
@Middleware(
validator(
{
name: Joi.string(),
email: Joi.string().required()
},
"body"
)
)
async put(req: Request, res: Response) {
res
.status(CREATED)
.json({ success: true, message: "user-created" });
}
}
The above example validates req.body
and uses the following validator
middleware:
import { Request, Response, NextFunction } from "express";
import Joi from "@hapi/joi";
export const validator = (
schemaMap: Joi.SchemaMap,
type: "body" | "params" | "query"
) => {
return (req: Request, res: Response, next: NextFunction) => {
let data: any;
switch (type) {
case "params":
data = req.params;
break;
case "query":
data = req.query;
break;
default:
data = req.body;
break;
}
const schema = Joi.object().keys(schemaMap);
const result = Joi.validate(data, schema);
if (result.error) throw new Error(`joi:${JSON.stringify(result.error)}`);
next();
};
};
from overnight.
Hey man sorry for the late response but I think you using express validators wrong. You forgot this line
validationResult(req).throw();
. I added an example to the sample-project and it's working fine.
@Get('debug/express-validators')
@Middleware(check('name').exists())
private async practiceValidators(req: Request, res: Response) {
try {
validationResult(req).throw();
return res.status(OK).json({
message: 'Hello from NodeJS ' + req.body.name,
});
} catch (err) {
Logger.Err(err, true);
return res.status(BAD_REQUEST).json({
error: err.message,
});
}
}
from overnight.
Related Issues (20)
- 404 status on every route
- Overnightjs not generating sourcemap at all
- How to use JwtManager.middleware? HOT 3
- Question: TypeScript Configuration / getOwnMetadata() returns undefined HOT 7
- AddControllers not working HOT 9
- Unable to access "this" inside controllers HOT 5
- 'Server' no longer exported HOT 2
- Why not async-wrap everything by default? HOT 2
- IRouter error when build HOT 1
- JWT Middleware HOT 1
- 404 on all routes when using express-promise-router HOT 4
- Non-blocking file logging HOT 1
- Problem with @ClassErrorMiddleware HOT 2
- Help wanted: Setting up controllers: {ControllerName} HOT 3
- How to get type safe on req.params HOT 1
- overnight breaks when controllers and server are in separate projects.
- Not an issue: Thank you for this project HOT 1
- OvernightJS controllers cannot be extended
- Controller with multiple enpoint
- Is this repository deprecated? HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from overnight.