Validation using JavaScript decorators

Jonathan Harrison
1 min readNov 1, 2017

--

Whilst searching for a validation library to use in one of my projects, I came across the class-validator module. After reading class-validators’s documentation and playing around with it, I really liked how easy it was to use and found it suited my needs well, so thought I would share.

class-validator uses the popular validator.js module to actually perform validation but what sets it apart is how you define your validation which is with JavaScript decorators. For anyone who has used C#, it is very familiar to using Data Annotations.

To cut to the chase over on my GitHub, there is a sample showing how to use class-validation in TypeScript. If you want to set it up for yourself then read on.

Setup

If you want to use class-validator with TypeScript, you need to enable Decorators. At the time of writing Decorators are an experimental feature and need to be enabled using a compiler flag; the TypeScript documentation shows you to enable this with:

"experimentalDecorators": true

Now install class-validator with npm or yarn.

Defining the validation

With the setup complete, its time to define your validation using a class. The Site class I have defined represents a site in a Password Manager type app:

Site class with validation

Usage

Now to use this class, simply create an instance of it and then call the validate method from class-validator; this returns an array of validation errors which you can then use to display in a UI for example.

Calling validate

--

--

Jonathan Harrison
Jonathan Harrison

Written by Jonathan Harrison

Principal Software Engineer @ Tripadvisor. Formerly at Spotify, Altitude Angel and Microsoft. All opinions are my own.

No responses yet