Validating Typescript Data Transfer Objects with Firefly Semantics Validator

Ole Ersoy
2 min readNov 12, 2021

--

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

--

--

Ole Ersoy

Founder of Firefly Semantics Corporation