Is it possible to validate single route parameter?Validate decimal numbers in JavaScript - IsNumeric()How to validate an email address in JavaScript(Built-in) way in JavaScript to check if a string is a valid numberWhen to use double or single quotes in JavaScript?Set a default parameter value for a JavaScript functionHow to get the value from the GET parameters?How to retrieve POST query parameters?Are strongly-typed functions as parameters possible in TypeScript?What is the difference between angular-route and angular-ui-router?Is it possible to apply CSS to half of a character?
How does encoder decoder network works?
Could this kind of inaccurate sacrifice be countered?
"Opusculum hoc, quamdiu vixero, doctioribus emendandum offero."?
What stops you from using fixed income in developing countries?
Where does learning new skills fit into Agile?
Nothing like a good ol' game of ModTen
What is the loud noise of a helicopter when the rotors are not yet moving?
Removal of て in Japanese novels
How can I unambiguously ask for a new user's "Display Name"?
Limitations with dynamical systems vs. PDEs?
Billiard balls collision
Do Bayesian credible intervals treat the estimated parameter as a random variable?
What are the occurences of total war in the Native Americans?
Was the Boeing 2707 design flawed?
Why does Windows store Wi-Fi passwords in a reversible format?
How does the OS tell whether an "Address is already in use"?
Breaker Mapping Questions
Higman's lemma and a manuscript of Erdős and Rado
Macro inserted via everypar in obeylines context doesn't see some commands
Joining lists with same elements
Tex Quotes(UVa 272)
Book with the Latin quote 'nihil superbus' meaning 'nothing above us'
Why doesn't 'd /= d' throw a division by zero exception?
When one problem is added to the previous one
Is it possible to validate single route parameter?
Validate decimal numbers in JavaScript - IsNumeric()How to validate an email address in JavaScript(Built-in) way in JavaScript to check if a string is a valid numberWhen to use double or single quotes in JavaScript?Set a default parameter value for a JavaScript functionHow to get the value from the GET parameters?How to retrieve POST query parameters?Are strongly-typed functions as parameters possible in TypeScript?What is the difference between angular-route and angular-ui-router?Is it possible to apply CSS to half of a character?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
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?
javascript node.js typescript nestjs class-validator
add a comment |
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?
javascript node.js typescript nestjs class-validator
add a comment |
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?
javascript node.js typescript nestjs class-validator
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?
javascript node.js typescript nestjs class-validator
javascript node.js typescript nestjs class-validator
edited Mar 27 at 22:30
Kim Kern
15.1k6 gold badges43 silver badges69 bronze badges
15.1k6 gold badges43 silver badges69 bronze badges
asked Mar 27 at 19:24
bloo79bloo79
257 bronze badges
257 bronze badges
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
The problem is that you have a plain string here. For the validation with class-validator
to work, you must instantiate a class, in your case ResourceId
. The built-in ValidationPipe
expects the value to be id: '123'
instead '123'
to be able to transform it automatically. But you can easily create your own validation pipe, that does this extra transformation.
export class ParamValidationPipe implements PipeTransform
async transform(value, metadata: ArgumentMetadata)
if (metadata.type === 'param')
// This is the relevant part: value -> id: value
const valueInstance = plainToClass(metadata.metatype, id: value );
const validationErrors = await validate(valueInstance);
if (validationErrors.length > 0)
throw new BadRequestException(validationErrors, 'Invalid route param');
return valueInstance;
else
return value;
You can then use it on your controller:
@UsePipes(ParamValidationPipe)
@Get(':companyId/departments/:departmentId/employees')
getEmployees(
@Param('companyId') companyId: ResourceId,
@Param('departmentId') departmentId: ResourceId,
)
return `id1: $companyId.id, id2: $departmentId.id`;
1
You can also use class-transformer-validator to do all the transformation, validation and checking the error list steps in one call :)
– quezak
Mar 29 at 13:49
Good point. :-) I'm not gonna change my answer because adding the notes about installing another package would make it even longer, but I think it's a very useful comment.
– Kim Kern
Mar 29 at 13:53
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55385041%2fis-it-possible-to-validate-single-route-parameter%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
The problem is that you have a plain string here. For the validation with class-validator
to work, you must instantiate a class, in your case ResourceId
. The built-in ValidationPipe
expects the value to be id: '123'
instead '123'
to be able to transform it automatically. But you can easily create your own validation pipe, that does this extra transformation.
export class ParamValidationPipe implements PipeTransform
async transform(value, metadata: ArgumentMetadata)
if (metadata.type === 'param')
// This is the relevant part: value -> id: value
const valueInstance = plainToClass(metadata.metatype, id: value );
const validationErrors = await validate(valueInstance);
if (validationErrors.length > 0)
throw new BadRequestException(validationErrors, 'Invalid route param');
return valueInstance;
else
return value;
You can then use it on your controller:
@UsePipes(ParamValidationPipe)
@Get(':companyId/departments/:departmentId/employees')
getEmployees(
@Param('companyId') companyId: ResourceId,
@Param('departmentId') departmentId: ResourceId,
)
return `id1: $companyId.id, id2: $departmentId.id`;
1
You can also use class-transformer-validator to do all the transformation, validation and checking the error list steps in one call :)
– quezak
Mar 29 at 13:49
Good point. :-) I'm not gonna change my answer because adding the notes about installing another package would make it even longer, but I think it's a very useful comment.
– Kim Kern
Mar 29 at 13:53
add a comment |
The problem is that you have a plain string here. For the validation with class-validator
to work, you must instantiate a class, in your case ResourceId
. The built-in ValidationPipe
expects the value to be id: '123'
instead '123'
to be able to transform it automatically. But you can easily create your own validation pipe, that does this extra transformation.
export class ParamValidationPipe implements PipeTransform
async transform(value, metadata: ArgumentMetadata)
if (metadata.type === 'param')
// This is the relevant part: value -> id: value
const valueInstance = plainToClass(metadata.metatype, id: value );
const validationErrors = await validate(valueInstance);
if (validationErrors.length > 0)
throw new BadRequestException(validationErrors, 'Invalid route param');
return valueInstance;
else
return value;
You can then use it on your controller:
@UsePipes(ParamValidationPipe)
@Get(':companyId/departments/:departmentId/employees')
getEmployees(
@Param('companyId') companyId: ResourceId,
@Param('departmentId') departmentId: ResourceId,
)
return `id1: $companyId.id, id2: $departmentId.id`;
1
You can also use class-transformer-validator to do all the transformation, validation and checking the error list steps in one call :)
– quezak
Mar 29 at 13:49
Good point. :-) I'm not gonna change my answer because adding the notes about installing another package would make it even longer, but I think it's a very useful comment.
– Kim Kern
Mar 29 at 13:53
add a comment |
The problem is that you have a plain string here. For the validation with class-validator
to work, you must instantiate a class, in your case ResourceId
. The built-in ValidationPipe
expects the value to be id: '123'
instead '123'
to be able to transform it automatically. But you can easily create your own validation pipe, that does this extra transformation.
export class ParamValidationPipe implements PipeTransform
async transform(value, metadata: ArgumentMetadata)
if (metadata.type === 'param')
// This is the relevant part: value -> id: value
const valueInstance = plainToClass(metadata.metatype, id: value );
const validationErrors = await validate(valueInstance);
if (validationErrors.length > 0)
throw new BadRequestException(validationErrors, 'Invalid route param');
return valueInstance;
else
return value;
You can then use it on your controller:
@UsePipes(ParamValidationPipe)
@Get(':companyId/departments/:departmentId/employees')
getEmployees(
@Param('companyId') companyId: ResourceId,
@Param('departmentId') departmentId: ResourceId,
)
return `id1: $companyId.id, id2: $departmentId.id`;
The problem is that you have a plain string here. For the validation with class-validator
to work, you must instantiate a class, in your case ResourceId
. The built-in ValidationPipe
expects the value to be id: '123'
instead '123'
to be able to transform it automatically. But you can easily create your own validation pipe, that does this extra transformation.
export class ParamValidationPipe implements PipeTransform
async transform(value, metadata: ArgumentMetadata)
if (metadata.type === 'param')
// This is the relevant part: value -> id: value
const valueInstance = plainToClass(metadata.metatype, id: value );
const validationErrors = await validate(valueInstance);
if (validationErrors.length > 0)
throw new BadRequestException(validationErrors, 'Invalid route param');
return valueInstance;
else
return value;
You can then use it on your controller:
@UsePipes(ParamValidationPipe)
@Get(':companyId/departments/:departmentId/employees')
getEmployees(
@Param('companyId') companyId: ResourceId,
@Param('departmentId') departmentId: ResourceId,
)
return `id1: $companyId.id, id2: $departmentId.id`;
edited Mar 29 at 13:58
answered Mar 27 at 22:30
Kim KernKim Kern
15.1k6 gold badges43 silver badges69 bronze badges
15.1k6 gold badges43 silver badges69 bronze badges
1
You can also use class-transformer-validator to do all the transformation, validation and checking the error list steps in one call :)
– quezak
Mar 29 at 13:49
Good point. :-) I'm not gonna change my answer because adding the notes about installing another package would make it even longer, but I think it's a very useful comment.
– Kim Kern
Mar 29 at 13:53
add a comment |
1
You can also use class-transformer-validator to do all the transformation, validation and checking the error list steps in one call :)
– quezak
Mar 29 at 13:49
Good point. :-) I'm not gonna change my answer because adding the notes about installing another package would make it even longer, but I think it's a very useful comment.
– Kim Kern
Mar 29 at 13:53
1
1
You can also use class-transformer-validator to do all the transformation, validation and checking the error list steps in one call :)
– quezak
Mar 29 at 13:49
You can also use class-transformer-validator to do all the transformation, validation and checking the error list steps in one call :)
– quezak
Mar 29 at 13:49
Good point. :-) I'm not gonna change my answer because adding the notes about installing another package would make it even longer, but I think it's a very useful comment.
– Kim Kern
Mar 29 at 13:53
Good point. :-) I'm not gonna change my answer because adding the notes about installing another package would make it even longer, but I think it's a very useful comment.
– Kim Kern
Mar 29 at 13:53
add a comment |
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55385041%2fis-it-possible-to-validate-single-route-parameter%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown