I have been searching through the class-validators samples and documentation, but I have not been able to find the specific validation that I require.
Within my code, I have an array of object literals that each contain unique properties and values.
const comboItems = [{itemType: 'Entree'}, {itemType: 'Side'}, {itemType: 'Beverage'}];
My goal is to validate the following criteria for the comboItems array: it must not be empty, it must contain a minimum and maximum of 3 objects, and it must include one object with itemType === 'Entree', another with itemType === 'Side', and a third with itemType === 'Beverage'.
Below is the class I have created, which does not provide the correct validation:
import {validate, ArrayContains, ArrayNotEmpty, ArrayMinSize, ArrayMaxSize} from 'class-validator';
import { plainToClass } from 'class-transformer';
export class MealMenuItem {
@ArrayContains([{itemType: 'Entree'}, {itemType: 'Side'}, {itemType: 'Beverage'}])
@ArrayNotEmpty()
@ArrayMinSize(3)
@ArrayMaxSize(3)
comboItems: any[];
}
const mealMenuItemData: any = {comboItems: [{itemType: 'Entree'}, {itemType: 'Side'}, {itemType: 'Beverage'}]};
const mealMenuItemDataClassInstance = plainToClass(MealMenuItem, mealMenuItemData as MealMenuItem)
validate(mealMenuItemDataClassInstance).then(errors => {
if (errors.length > 0)
console.log('validation failed. errors: ', JSON.stringify(errors));
else
console.log('validation succeed');
});
If anyone can offer assistance, I would greatly appreciate it!