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

          How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

          155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

          Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?