'Is it possible to validate single route parameter?
Let's say I have following route:
companies/{companyId}/departments/{departmentId}/employees
Is it possible to validate both resources ids (companyId, departmentId) separately? I've tried following but it's not working.
class ResourceId {
@IsNumberString()
@StringNumberRange(...) // my custom validator
id: number;
}
@Get(':companyId/departments/:departmentId/employees')
getEmployees(
@Param('companyId') companyId: ResourceId,
@Param('departmentId') departmentId: ResourceId,
) {}
I have multiple cases when there is more than one parameter in the single route. I would not like to create separate validation class for every route. Is there a way to handle this problem in a different way?
Solution 1:[1]
As of 2022, NestJS docs say that it's possible to validate route params using the built-in validation pipe.
In a controller:
@Get(':id')
findOne(@Param() params: FindOneParams) {
return 'This action returns a user';
}
Validation class:
import { IsNumberString } from 'class-validator';
export class FindOneParams {
@IsNumberString()
id: number;
}
Ref: https://docs.nestjs.com/techniques/validation#auto-validation
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | asologor |
