Kishore Kumar Korada
Kishore Kumar Korada

Reputation: 1264

How to perform Joi Validations for a TypeScript Class?

I'm able to perform Joi Validations for function expressions in node as shown below

export var shippingInfo = Joi.object().keys({
   expectedDeliveryDate:Joi.date().required(),
   isRegisteredCompanyAddress:Joi.number().required(),
   addressLine:Joi.string(),
   country:Joi.string(),
   state:Joi.string(),
   city:Joi.string(),
   zipcode:Joi.string()
});

But the problem is, I recently started working on typescript. So here, I've few classes and I'm supposed to perform the Joi validations as I did in the above function expressions. i.e I want to validate for the below class

export class ShippingInfo {
   expectedDeliveryDate: Date,
   isRegisteredCompanyAddress: number,
   addressLine:string,
   country:string,
   state:string,
   city:string,
   zipcode:string
}

How should I make validations for the above class. Should do validations for class level or it's object level? how?

Upvotes: 6

Views: 12167

Answers (2)

Alexey Baranoshnikov
Alexey Baranoshnikov

Reputation: 105

You can use class-from-any, tsdv-joi, class-validator or class-transformer.

Example from class-from-any where we get, convert and validate JSON data as typescript class:

import { FromAny, GetFrom, Validate, isString, notEmpty } from "class-from-any";

const worldJSONData = `{"name": "Earth"}`;

class World extends FromAny {
    @GetFrom("name") @Validate(isString, notEmpty) title: string;
}

const world = new World().from(
    JSON.parse(worldJSONData) as Record<string, unknown>
);

Upvotes: 1

MehulJoshi
MehulJoshi

Reputation: 889

you can use this project as a reference. tsdv-joi

// ...imports...

registerJoi(Joi);

class MyClass {
    @Max(5)
    @Min(2)
    @StringSchema
    public myProperty : string;
}

let instance = new MyClass();
instance.myProperty = "a";

const validator = new Validator();
var result = validator.validate(instance);
console.log(result); // outputs the Joi returned value

If you need npm package then you can use this wrapper for it gearworks

Upvotes: 3

Related Questions