Validating Typescript Data Transfer Objects with Firefly Semantics Validator

Image by Gerhard G. from Pixabay

Updated Version

There’s an updated version of this article here:

Scenario

We are receiving data transfer object instances with a PurchaseOrderDTO type and we need to validate them using Firefly Semantics Validator:

Approach

The PurchaseOrderDTO has been annotated with Firefly Semantics Validator validation annotations as follows:

We will create an instance an validate it:

const poDTOValid: PurchaseOrderDTO = new PurchaseOrderDTO(
{
sku: 'skuABC',
id: '123',
purchaseDate: '2021-11-22',
receiptDate: '2021-11-28',
quantity: '2',
});
const oeValid: ObjectErrors = validate(poDTOValid);
assert.equal(oeValid.errors.length, 0, 'There should be 0 errors');

In this case there are no errors, as all the properties are valid.

Lets create another instance with no valid properties:

const poDTOInvalid1: PurchaseOrderDTO = new PurchaseOrderDTO({});
const oeInvalid: ObjectErrors = validate(poDTOInvalid1);
assert.equal(oeInvalid.errors.length, 5, 'There should be 5 errors');

In this case the @IsDefined annotation is triggered 5 times, creating 5 ValidationError errors.

Demo

Related Concepts

Founder of Firefly Semantics Corporation

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Common Array methods in JavaScript

Multiple appsettings.json in .net core without using an environment variable

Build forms in React Native with tcomb-form-native

Custom font with React Native

What the Heck is an API?! Featuring NodeJS

Dj Scratch Sound Effect Free Download4

What is DOM using JavaScript?

Web Performance Profiling: Instacart

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ole Ersoy

Ole Ersoy

Founder of Firefly Semantics Corporation

More from Medium

Handling Protractor Control Flow Deprecation

Sorting Javascript Objects in Ascending Order by Date

Features of Different Javascript Framework : Node Js, BackBone JS, Ext Js

JavaScript Control Flow & Error Handling