Joi validate optional array from dynamically added fields












1















I have a form where the user can add more authors, the first one is required and is it has a its own fields validation



When the user add more authors these authors are stored in an array, so if the user does not add more authors it shows this error message:



""authors_first_name" must be an array"
""authors_last_name" must be an array"
""authors_country" must be an array"


How to make the array optional when thare are not more than one author?
But required when authors are added?



const schema = Joi.object().keys({
author_first_name: Joi.string().required().error(() => 'Author First Name is required'),
author_last_name: Joi.string().required().error(() => 'Author Last Name is required'),
author_country: Joi.string().valid(isoCodes).error(() => 'Author Country not valid'),

authors_first_name: Joi.array().items(Joi.string()).optional(),
authors_last_name: Joi.array().items(Joi.string()).optional(),
authors_country: Joi.array().items(Joi.string().valid(isoCodes).error(() => 'Country not valid')).optional()
});


I added the .optional() but the error keeps showing










share|improve this question



























    1















    I have a form where the user can add more authors, the first one is required and is it has a its own fields validation



    When the user add more authors these authors are stored in an array, so if the user does not add more authors it shows this error message:



    ""authors_first_name" must be an array"
    ""authors_last_name" must be an array"
    ""authors_country" must be an array"


    How to make the array optional when thare are not more than one author?
    But required when authors are added?



    const schema = Joi.object().keys({
    author_first_name: Joi.string().required().error(() => 'Author First Name is required'),
    author_last_name: Joi.string().required().error(() => 'Author Last Name is required'),
    author_country: Joi.string().valid(isoCodes).error(() => 'Author Country not valid'),

    authors_first_name: Joi.array().items(Joi.string()).optional(),
    authors_last_name: Joi.array().items(Joi.string()).optional(),
    authors_country: Joi.array().items(Joi.string().valid(isoCodes).error(() => 'Country not valid')).optional()
    });


    I added the .optional() but the error keeps showing










    share|improve this question

























      1












      1








      1








      I have a form where the user can add more authors, the first one is required and is it has a its own fields validation



      When the user add more authors these authors are stored in an array, so if the user does not add more authors it shows this error message:



      ""authors_first_name" must be an array"
      ""authors_last_name" must be an array"
      ""authors_country" must be an array"


      How to make the array optional when thare are not more than one author?
      But required when authors are added?



      const schema = Joi.object().keys({
      author_first_name: Joi.string().required().error(() => 'Author First Name is required'),
      author_last_name: Joi.string().required().error(() => 'Author Last Name is required'),
      author_country: Joi.string().valid(isoCodes).error(() => 'Author Country not valid'),

      authors_first_name: Joi.array().items(Joi.string()).optional(),
      authors_last_name: Joi.array().items(Joi.string()).optional(),
      authors_country: Joi.array().items(Joi.string().valid(isoCodes).error(() => 'Country not valid')).optional()
      });


      I added the .optional() but the error keeps showing










      share|improve this question














      I have a form where the user can add more authors, the first one is required and is it has a its own fields validation



      When the user add more authors these authors are stored in an array, so if the user does not add more authors it shows this error message:



      ""authors_first_name" must be an array"
      ""authors_last_name" must be an array"
      ""authors_country" must be an array"


      How to make the array optional when thare are not more than one author?
      But required when authors are added?



      const schema = Joi.object().keys({
      author_first_name: Joi.string().required().error(() => 'Author First Name is required'),
      author_last_name: Joi.string().required().error(() => 'Author Last Name is required'),
      author_country: Joi.string().valid(isoCodes).error(() => 'Author Country not valid'),

      authors_first_name: Joi.array().items(Joi.string()).optional(),
      authors_last_name: Joi.array().items(Joi.string()).optional(),
      authors_country: Joi.array().items(Joi.string().valid(isoCodes).error(() => 'Country not valid')).optional()
      });


      I added the .optional() but the error keeps showing







      node.js hapijs joi






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 24 '18 at 16:08









      tttonytttony

      2,42121832




      2,42121832
























          2 Answers
          2






          active

          oldest

          votes


















          1














          I think the approach you are using here is misleading, you should have array of objects even if the user inserts only one author or multiple authors. Taking different arrays for first_name and last_name can result in problems like what if you got 5 first_names and 6 last_names. you can add validations but still this is a kind of buggy approach. You should use schema like this



              const schema = Joi.array().required().items(
          Joi.object().required().keys({
          author_first_name: Joi.string().required().error(() => 'Author First Name is required'),
          author_last_name: Joi.string().required().error(() => 'Author Last Name is required'),
          author_country: Joi.string().valid(isoCodes).error(() => 'Author Country not valid'),
          }))





          share|improve this answer































            0














            Alright I got it working with this code:



            const schema = Joi.object().keys({
            first: Joi.array().items(Joi.string()).single(),
            last: Joi.array().items(Joi.string()).single(),
            country: Joi.array().items(Joi.string().valid(isoCodes)).single(),
            }).assert('first.length', Joi.ref('last.length'))
            .assert('last.length', Joi.ref('country.length'));


            Two additions to my original code:





            1. .single() to the array().items(), this will accept string and arrays in the values


            2. .assert() to check if the array length are equals


            Thanks to this post, test code here






            share|improve this answer























              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%2f53459981%2fjoi-validate-optional-array-from-dynamically-added-fields%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              1














              I think the approach you are using here is misleading, you should have array of objects even if the user inserts only one author or multiple authors. Taking different arrays for first_name and last_name can result in problems like what if you got 5 first_names and 6 last_names. you can add validations but still this is a kind of buggy approach. You should use schema like this



                  const schema = Joi.array().required().items(
              Joi.object().required().keys({
              author_first_name: Joi.string().required().error(() => 'Author First Name is required'),
              author_last_name: Joi.string().required().error(() => 'Author Last Name is required'),
              author_country: Joi.string().valid(isoCodes).error(() => 'Author Country not valid'),
              }))





              share|improve this answer




























                1














                I think the approach you are using here is misleading, you should have array of objects even if the user inserts only one author or multiple authors. Taking different arrays for first_name and last_name can result in problems like what if you got 5 first_names and 6 last_names. you can add validations but still this is a kind of buggy approach. You should use schema like this



                    const schema = Joi.array().required().items(
                Joi.object().required().keys({
                author_first_name: Joi.string().required().error(() => 'Author First Name is required'),
                author_last_name: Joi.string().required().error(() => 'Author Last Name is required'),
                author_country: Joi.string().valid(isoCodes).error(() => 'Author Country not valid'),
                }))





                share|improve this answer


























                  1












                  1








                  1







                  I think the approach you are using here is misleading, you should have array of objects even if the user inserts only one author or multiple authors. Taking different arrays for first_name and last_name can result in problems like what if you got 5 first_names and 6 last_names. you can add validations but still this is a kind of buggy approach. You should use schema like this



                      const schema = Joi.array().required().items(
                  Joi.object().required().keys({
                  author_first_name: Joi.string().required().error(() => 'Author First Name is required'),
                  author_last_name: Joi.string().required().error(() => 'Author Last Name is required'),
                  author_country: Joi.string().valid(isoCodes).error(() => 'Author Country not valid'),
                  }))





                  share|improve this answer













                  I think the approach you are using here is misleading, you should have array of objects even if the user inserts only one author or multiple authors. Taking different arrays for first_name and last_name can result in problems like what if you got 5 first_names and 6 last_names. you can add validations but still this is a kind of buggy approach. You should use schema like this



                      const schema = Joi.array().required().items(
                  Joi.object().required().keys({
                  author_first_name: Joi.string().required().error(() => 'Author First Name is required'),
                  author_last_name: Joi.string().required().error(() => 'Author Last Name is required'),
                  author_country: Joi.string().valid(isoCodes).error(() => 'Author Country not valid'),
                  }))






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 26 '18 at 5:27









                  Ganesh KarewadGanesh Karewad

                  447513




                  447513

























                      0














                      Alright I got it working with this code:



                      const schema = Joi.object().keys({
                      first: Joi.array().items(Joi.string()).single(),
                      last: Joi.array().items(Joi.string()).single(),
                      country: Joi.array().items(Joi.string().valid(isoCodes)).single(),
                      }).assert('first.length', Joi.ref('last.length'))
                      .assert('last.length', Joi.ref('country.length'));


                      Two additions to my original code:





                      1. .single() to the array().items(), this will accept string and arrays in the values


                      2. .assert() to check if the array length are equals


                      Thanks to this post, test code here






                      share|improve this answer




























                        0














                        Alright I got it working with this code:



                        const schema = Joi.object().keys({
                        first: Joi.array().items(Joi.string()).single(),
                        last: Joi.array().items(Joi.string()).single(),
                        country: Joi.array().items(Joi.string().valid(isoCodes)).single(),
                        }).assert('first.length', Joi.ref('last.length'))
                        .assert('last.length', Joi.ref('country.length'));


                        Two additions to my original code:





                        1. .single() to the array().items(), this will accept string and arrays in the values


                        2. .assert() to check if the array length are equals


                        Thanks to this post, test code here






                        share|improve this answer


























                          0












                          0








                          0







                          Alright I got it working with this code:



                          const schema = Joi.object().keys({
                          first: Joi.array().items(Joi.string()).single(),
                          last: Joi.array().items(Joi.string()).single(),
                          country: Joi.array().items(Joi.string().valid(isoCodes)).single(),
                          }).assert('first.length', Joi.ref('last.length'))
                          .assert('last.length', Joi.ref('country.length'));


                          Two additions to my original code:





                          1. .single() to the array().items(), this will accept string and arrays in the values


                          2. .assert() to check if the array length are equals


                          Thanks to this post, test code here






                          share|improve this answer













                          Alright I got it working with this code:



                          const schema = Joi.object().keys({
                          first: Joi.array().items(Joi.string()).single(),
                          last: Joi.array().items(Joi.string()).single(),
                          country: Joi.array().items(Joi.string().valid(isoCodes)).single(),
                          }).assert('first.length', Joi.ref('last.length'))
                          .assert('last.length', Joi.ref('country.length'));


                          Two additions to my original code:





                          1. .single() to the array().items(), this will accept string and arrays in the values


                          2. .assert() to check if the array length are equals


                          Thanks to this post, test code here







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 27 '18 at 1:13









                          tttonytttony

                          2,42121832




                          2,42121832






























                              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%2f53459981%2fjoi-validate-optional-array-from-dynamically-added-fields%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

                              Wiesbaden

                              Marschland

                              Dieringhausen