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;








2















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?










share|improve this question
































    2















    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?










    share|improve this question




























      2












      2








      2








      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?










      share|improve this question
















      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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      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

























          1 Answer
          1






          active

          oldest

          votes


















          1















          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`;






          share|improve this answer






















          • 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










          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
          );



          );













          draft saved

          draft discarded


















          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









          1















          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`;






          share|improve this answer






















          • 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















          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`;






          share|improve this answer






















          • 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










          1









          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`;






          share|improve this answer















          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`;







          share|improve this answer














          share|improve this answer



          share|improve this answer








          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












          • 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








          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.



















          draft saved

          draft discarded
















































          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.




          draft saved


          draft discarded














          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





















































          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







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현