乐闻世界logo
搜索文章和话题

How to validate array of literals using class-validator and class-transformer with plainToInstance or plainToClass

1个答案

1

In TypeScript, we often use the class-transformer library to convert plain JavaScript objects (literals) into class instances, and use the class-validator library to validate whether the properties of these objects conform to the expected rules. To implement your requirement of validating literal arrays, we can follow the steps below:

1. Install the necessary libraries

bash
npm install class-transformer class-validator

2. Create the class and validation rules

typescript
import { IsInt, Min, Max, ValidateNested } from 'class-validator'; import { Type } from 'class-transformer'; class Product { @IsInt() @Min(1) @Max(100) id: number; @IsInt() @Min(0) price: number; }

3. Use plainToInstance or plainToClass for conversion and validation

typescript
import { plainToInstance } from 'class-transformer'; import { validateSync, ValidationError } from 'class-validator'; // Example literal array const productsArray = [ { id: 10, price: 20 }, { id: 2, price: 5 }, { id: 110, price: -1 } // This object will not pass validation ]; // Convert and validate const products = plainToInstance(Product, productsArray); const errors = products.map(product => validateSync(product)); // Output error information errors.forEach((error, index) => { if (error.length > 0) { console.log(`Error in product ${index+1}:`, error.map(e => ({ property: e.property, constraints: e.constraints }))); } });

4. Handle validation errors

After validation, you can decide how to handle the errors based on the returned ValidationError array. For example, you can log errors, throw exceptions, or return an error response.

Practical Application Example

Suppose we have a backend system for an online store that needs to receive JSON data representing a product list, and this data must be validated before being stored in the database. We can create a RESTful API to receive product data, use the above methods to validate the data's validity, and only process or store valid data.

In summary

By doing this, we can ensure the correctness and consistency of the data, reducing issues caused by data errors. In summary, by effectively combining class-transformer and class-validator, we can meet complex data validation requirements and ensure data security and consistency.

2024年7月24日 10:01 回复

你的答案