Complex validation using Joi libraryValidate 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 numberComplex nesting of partials and templateshow to work range validators?how to create a range validator using javascript? not use range validator control in VSWhen using Joi with Hapi, how does one setup a require on one key but allow any and all other keys?Require at least one non-null child in joi object that allows nullHow to stripUnknown using HapiJS Joi and SequelizeJS?JOI - Validating complex object

Denied entry in Croatia Border

tikz: draw multicolor curve with smooth gradient

Active wildlife outside the window- Good or Bad for Cat psychology?

Is it advisable to inform the CEO about his brother accessing his office?

What's the point of stochastic volatiliy models if you can use local volatility?

Why would Dementors torture a Death Eater if they are loyal to Voldemort?

Avoiding repetition when using the "snprintf idiom" to write text

How do I tell my girlfriend she's been buying me books by the wrong author for the last nine months?

What's the idiomatic (or best) way to trim surrounding whitespace from a string?

Simplify the code

Why will we fail creating a self sustaining off world colony?

Do electrons really perform instantaneous quantum leaps?

What does 'in attendance' mean on an England death certificate?

How to count the number of bytes in a file, grouping the same bytes?

Tikz Payoff Matrix

Disk usage confusion: 10G missing on Linux home partition on SSD

How does mmorpg store data?

Why doesn't SpaceX land boosters in Africa?

Why do movie directors use brown tint on Mexico cities?

What verb goes with "coup"?

ATMEGA328P-U vs ATMEGA328-PU

What's the overlapping calendar of two different lunar cycles

Which are more efficient in putting out wildfires: planes or helicopters?

How far can gerrymandering go?



Complex validation using Joi library


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 numberComplex nesting of partials and templateshow to work range validators?how to create a range validator using javascript? not use range validator control in VSWhen using Joi with Hapi, how does one setup a require on one key but allow any and all other keys?Require at least one non-null child in joi object that allows nullHow to stripUnknown using HapiJS Joi and SequelizeJS?JOI - Validating complex object













1















I have this json:



let purchaseSubscription = 
'metadata':
'eventName': 'PurchaseSubscription',
'type': 'setup' // setup, repurchase or recurring
,
'data':
'subscriptionId': '447481',
'subscriptionTrialId': '23542'

;


If the metadata.type has value setup
then data.subscriptionTrialId should be validated for existence and to be a number.
If the metadata.type has other values, the data.subscriptionTrialId can be ignored.



This is what I currently have:



const Joi = require('joi');
const validTypes = ['setup', 'repurchase', 'recurring'];

exports.schema = Joi.object().keys(
metadata: Joi.object(
eventName: Joi.string().required(),
type: Joi.string().valid(validTypes).required()
).required(),
data: Joi.object(
subscriptionId: Joi.number().integer().min(1).max(2147483647).required(),
subscriptionTrialId: Joi.when(
'metadata.type', is: 'setup', then: Joi.required() )
).required()
).options( 'allowUnknown': true );


But I am not getting desired results. The data.subscriptionTrialId is always validated, no matter what I have under metadata.type



I tried reading documentation, but can't make it to work :(










share|improve this question




























    1















    I have this json:



    let purchaseSubscription = 
    'metadata':
    'eventName': 'PurchaseSubscription',
    'type': 'setup' // setup, repurchase or recurring
    ,
    'data':
    'subscriptionId': '447481',
    'subscriptionTrialId': '23542'

    ;


    If the metadata.type has value setup
    then data.subscriptionTrialId should be validated for existence and to be a number.
    If the metadata.type has other values, the data.subscriptionTrialId can be ignored.



    This is what I currently have:



    const Joi = require('joi');
    const validTypes = ['setup', 'repurchase', 'recurring'];

    exports.schema = Joi.object().keys(
    metadata: Joi.object(
    eventName: Joi.string().required(),
    type: Joi.string().valid(validTypes).required()
    ).required(),
    data: Joi.object(
    subscriptionId: Joi.number().integer().min(1).max(2147483647).required(),
    subscriptionTrialId: Joi.when(
    'metadata.type', is: 'setup', then: Joi.required() )
    ).required()
    ).options( 'allowUnknown': true );


    But I am not getting desired results. The data.subscriptionTrialId is always validated, no matter what I have under metadata.type



    I tried reading documentation, but can't make it to work :(










    share|improve this question


























      1












      1








      1








      I have this json:



      let purchaseSubscription = 
      'metadata':
      'eventName': 'PurchaseSubscription',
      'type': 'setup' // setup, repurchase or recurring
      ,
      'data':
      'subscriptionId': '447481',
      'subscriptionTrialId': '23542'

      ;


      If the metadata.type has value setup
      then data.subscriptionTrialId should be validated for existence and to be a number.
      If the metadata.type has other values, the data.subscriptionTrialId can be ignored.



      This is what I currently have:



      const Joi = require('joi');
      const validTypes = ['setup', 'repurchase', 'recurring'];

      exports.schema = Joi.object().keys(
      metadata: Joi.object(
      eventName: Joi.string().required(),
      type: Joi.string().valid(validTypes).required()
      ).required(),
      data: Joi.object(
      subscriptionId: Joi.number().integer().min(1).max(2147483647).required(),
      subscriptionTrialId: Joi.when(
      'metadata.type', is: 'setup', then: Joi.required() )
      ).required()
      ).options( 'allowUnknown': true );


      But I am not getting desired results. The data.subscriptionTrialId is always validated, no matter what I have under metadata.type



      I tried reading documentation, but can't make it to work :(










      share|improve this question
















      I have this json:



      let purchaseSubscription = 
      'metadata':
      'eventName': 'PurchaseSubscription',
      'type': 'setup' // setup, repurchase or recurring
      ,
      'data':
      'subscriptionId': '447481',
      'subscriptionTrialId': '23542'

      ;


      If the metadata.type has value setup
      then data.subscriptionTrialId should be validated for existence and to be a number.
      If the metadata.type has other values, the data.subscriptionTrialId can be ignored.



      This is what I currently have:



      const Joi = require('joi');
      const validTypes = ['setup', 'repurchase', 'recurring'];

      exports.schema = Joi.object().keys(
      metadata: Joi.object(
      eventName: Joi.string().required(),
      type: Joi.string().valid(validTypes).required()
      ).required(),
      data: Joi.object(
      subscriptionId: Joi.number().integer().min(1).max(2147483647).required(),
      subscriptionTrialId: Joi.when(
      'metadata.type', is: 'setup', then: Joi.required() )
      ).required()
      ).options( 'allowUnknown': true );


      But I am not getting desired results. The data.subscriptionTrialId is always validated, no matter what I have under metadata.type



      I tried reading documentation, but can't make it to work :(







      javascript node.js joi






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 25 at 16:39







      Vedran Maricevic.

















      asked Mar 25 at 16:32









      Vedran Maricevic.Vedran Maricevic.

      2,5324 gold badges38 silver badges65 bronze badges




      2,5324 gold badges38 silver badges65 bronze badges




















          1 Answer
          1






          active

          oldest

          votes


















          1














          You can use the otherwise key in the JOI schema.



          Somewhere in your code before declaring exports.schema:



          const trialIdRequired = Joi.object(
          subscriptionId: Joi.number().integer().min(1).max(2147483647).required(),
          subscriptionTrialId: Joi.required()
          ).required()

          const trialIdNotRequired = Joi.object(
          subscriptionId: Joi.number().integer().min(1).max(2147483647).required(),
          subscriptionTrialId: Joi.any()
          )


          And then add a when clause to the data field



          data: Joi.when(
          'metadata.type',

          is: 'setup',
          then: trialIdRequired,
          otherwise: trialIdNotRequired
          )






          share|improve this answer

























          • I plugged your example to the code, and for some reason it does not get validated at all, in other words it is ignored. Would you care to expand the answer, where I can see exactly what is going on? I have a feeling I am doing something silly :(

            – Vedran Maricevic.
            Mar 25 at 16:44






          • 1





            Oops my bad! Apparently Joi does not read siblings of parent in the when clause. Updating the answer to the alternate solution.

            – SerShubham
            Mar 25 at 17:09











          • Worked great. Thank you.

            – Vedran Maricevic.
            Mar 26 at 7:33










          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%2f55342432%2fcomplex-validation-using-joi-library%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














          You can use the otherwise key in the JOI schema.



          Somewhere in your code before declaring exports.schema:



          const trialIdRequired = Joi.object(
          subscriptionId: Joi.number().integer().min(1).max(2147483647).required(),
          subscriptionTrialId: Joi.required()
          ).required()

          const trialIdNotRequired = Joi.object(
          subscriptionId: Joi.number().integer().min(1).max(2147483647).required(),
          subscriptionTrialId: Joi.any()
          )


          And then add a when clause to the data field



          data: Joi.when(
          'metadata.type',

          is: 'setup',
          then: trialIdRequired,
          otherwise: trialIdNotRequired
          )






          share|improve this answer

























          • I plugged your example to the code, and for some reason it does not get validated at all, in other words it is ignored. Would you care to expand the answer, where I can see exactly what is going on? I have a feeling I am doing something silly :(

            – Vedran Maricevic.
            Mar 25 at 16:44






          • 1





            Oops my bad! Apparently Joi does not read siblings of parent in the when clause. Updating the answer to the alternate solution.

            – SerShubham
            Mar 25 at 17:09











          • Worked great. Thank you.

            – Vedran Maricevic.
            Mar 26 at 7:33















          1














          You can use the otherwise key in the JOI schema.



          Somewhere in your code before declaring exports.schema:



          const trialIdRequired = Joi.object(
          subscriptionId: Joi.number().integer().min(1).max(2147483647).required(),
          subscriptionTrialId: Joi.required()
          ).required()

          const trialIdNotRequired = Joi.object(
          subscriptionId: Joi.number().integer().min(1).max(2147483647).required(),
          subscriptionTrialId: Joi.any()
          )


          And then add a when clause to the data field



          data: Joi.when(
          'metadata.type',

          is: 'setup',
          then: trialIdRequired,
          otherwise: trialIdNotRequired
          )






          share|improve this answer

























          • I plugged your example to the code, and for some reason it does not get validated at all, in other words it is ignored. Would you care to expand the answer, where I can see exactly what is going on? I have a feeling I am doing something silly :(

            – Vedran Maricevic.
            Mar 25 at 16:44






          • 1





            Oops my bad! Apparently Joi does not read siblings of parent in the when clause. Updating the answer to the alternate solution.

            – SerShubham
            Mar 25 at 17:09











          • Worked great. Thank you.

            – Vedran Maricevic.
            Mar 26 at 7:33













          1












          1








          1







          You can use the otherwise key in the JOI schema.



          Somewhere in your code before declaring exports.schema:



          const trialIdRequired = Joi.object(
          subscriptionId: Joi.number().integer().min(1).max(2147483647).required(),
          subscriptionTrialId: Joi.required()
          ).required()

          const trialIdNotRequired = Joi.object(
          subscriptionId: Joi.number().integer().min(1).max(2147483647).required(),
          subscriptionTrialId: Joi.any()
          )


          And then add a when clause to the data field



          data: Joi.when(
          'metadata.type',

          is: 'setup',
          then: trialIdRequired,
          otherwise: trialIdNotRequired
          )






          share|improve this answer















          You can use the otherwise key in the JOI schema.



          Somewhere in your code before declaring exports.schema:



          const trialIdRequired = Joi.object(
          subscriptionId: Joi.number().integer().min(1).max(2147483647).required(),
          subscriptionTrialId: Joi.required()
          ).required()

          const trialIdNotRequired = Joi.object(
          subscriptionId: Joi.number().integer().min(1).max(2147483647).required(),
          subscriptionTrialId: Joi.any()
          )


          And then add a when clause to the data field



          data: Joi.when(
          'metadata.type',

          is: 'setup',
          then: trialIdRequired,
          otherwise: trialIdNotRequired
          )







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 25 at 17:22

























          answered Mar 25 at 16:38









          SerShubhamSerShubham

          5162 silver badges8 bronze badges




          5162 silver badges8 bronze badges












          • I plugged your example to the code, and for some reason it does not get validated at all, in other words it is ignored. Would you care to expand the answer, where I can see exactly what is going on? I have a feeling I am doing something silly :(

            – Vedran Maricevic.
            Mar 25 at 16:44






          • 1





            Oops my bad! Apparently Joi does not read siblings of parent in the when clause. Updating the answer to the alternate solution.

            – SerShubham
            Mar 25 at 17:09











          • Worked great. Thank you.

            – Vedran Maricevic.
            Mar 26 at 7:33

















          • I plugged your example to the code, and for some reason it does not get validated at all, in other words it is ignored. Would you care to expand the answer, where I can see exactly what is going on? I have a feeling I am doing something silly :(

            – Vedran Maricevic.
            Mar 25 at 16:44






          • 1





            Oops my bad! Apparently Joi does not read siblings of parent in the when clause. Updating the answer to the alternate solution.

            – SerShubham
            Mar 25 at 17:09











          • Worked great. Thank you.

            – Vedran Maricevic.
            Mar 26 at 7:33
















          I plugged your example to the code, and for some reason it does not get validated at all, in other words it is ignored. Would you care to expand the answer, where I can see exactly what is going on? I have a feeling I am doing something silly :(

          – Vedran Maricevic.
          Mar 25 at 16:44





          I plugged your example to the code, and for some reason it does not get validated at all, in other words it is ignored. Would you care to expand the answer, where I can see exactly what is going on? I have a feeling I am doing something silly :(

          – Vedran Maricevic.
          Mar 25 at 16:44




          1




          1





          Oops my bad! Apparently Joi does not read siblings of parent in the when clause. Updating the answer to the alternate solution.

          – SerShubham
          Mar 25 at 17:09





          Oops my bad! Apparently Joi does not read siblings of parent in the when clause. Updating the answer to the alternate solution.

          – SerShubham
          Mar 25 at 17:09













          Worked great. Thank you.

          – Vedran Maricevic.
          Mar 26 at 7:33





          Worked great. Thank you.

          – Vedran Maricevic.
          Mar 26 at 7:33






          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%2f55342432%2fcomplex-validation-using-joi-library%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

          Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

          Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript