Skip to content
Advertisement

class-validator – Validate that an array of strings matches a value

I’m using the class-validator npm package and would like to validate that the type property of request body matches one either ‘organization’ or ‘student’.

How would I do this with this package?

This doesn’t work:

@IsIn(['organization', 'student'])
type: string

Request body example:

{
   "type": "organization",
   "email": "email@email.com",
   "password": "veryscretpwd"
}

Advertisement

Answer

You can use something like this in your model class.

{
        "type": {
                type: String,
                enum: ['organization', 'student'],
                required: [true, 'Type is required.']
        },
        "email": ...
}

Instead of @IsIn use enum.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement