ReactJS: where to put validation logic in a form with "nested" composite components? -


i'm new reactjs , unsure best place put validation logic needed both nested child components in form, , overall "parent" form component itself. here over-simplified example illustrates question...

i have object represents pet owner:

{   name: 'jon arbuckle',   pets: [    { name: 'odie', type: 'dog' },    { name: 'garfield', type: 'cat' }   ] } 

i'm using composite component called <petownerform> render form editing data. <petownerform> renders this:

<input type="text" value={name} /> <petlist value={petowner.pets} /> 

<petlist> composite component renders this:

<petlistitem value={this.props.value[i]} />  // render each pet... // buttons adding/deleting pets 

<petlistitem> renders this:

<input type="text" value={this.props.value.name} /> <pettypepicker value={this.props.value.type} /> 

lastly, <pettypepicker> renders <select> <option>s pet types.

<pettypepicker> needs know how validate selected type can display inline error message (e.g., ensure value selected).

however, <petownerform> needs know how validate pet type because needs know how validate entire object (on load, each time form updated, , before submitting data server). if field invalid, "save" button should disabled.

so where, example, should "is valid pet type selected?" logic go? (bear in mind trivial example; in reality have many fields , nested composite components).

the options see far are:

a) replicate validation logic pet type (or whatever field) both in <petownerform> , <pettypepicker>. might matter of calling same, shared validation function in both places:

//petownerform.js: validate(petownerobj) {   util.ispettypevalid(petownerobj.pets[i]) // each pet   // validate other properties in petownerobj... }  //pettypepicker.js:   validate(pettype) {   util.ispettypevalid(pettype) } 

b) use custom petowner, pet, , pettype models have own validators. way can ask model validate itself, regardless of is. maybe this:

{   name: { value: 'jon arbuckle', isvalid: ()=>{...} },   pets: [   {     name: { value: 'garfield', isvalid: ()=>{...} },     type: { value: 'cat', isvalid: ()=>{...} }    },    ...   ] } 

c) modify petownerform.js go recurse pet owner object, validating each value, , setting 'errors' property child components can reference, resulting in object this:

{   name: { value: 'jon arbuckle asdfasdfasdf^^', errors: ['too many characters', 'contains invalid character']] },   pets: [     {       name: { value: '', errors: ['required value missing'] },       type: { value: 'tree', errors: ['invalid pet type'] }     },     ...   ] } 

which option recommended react apps (or there option)?


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -