- Clean entity validation and auto-mapping.
- Prevents overposting attacks.
- Simple and extensible.
Define your target model:
export class TargetModel {
requiredField: string = "";
optionalField: string | null = null;
}
And validate it! For example, if you want to check a request on ExpressJS:
const [targetModel, isValid, validationErrors] = validateModel(TargetModel, req.body);
if (!isValid) {
res.status(400).send(validationErrors);
} else {
const result = await doSomethingWithTargetModel({
additionalFields: true,
...command,
} as targetWithAdditionalFields)
res.send(result);
}
For more examples, see sample.ts. To run this project locally simply use these commands:
npm install
npm start
-
How to integrate this with my project? Just copy the contents from validator.ts into your project, extend and modify as required.
-
Why there is no NPM package? This is a base code that you can use, extend and customize so there isn't (and probably won't be) an available NPM package.