Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-nested-validation

Package Overview
Dependencies
Maintainers
1
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-nested-validation - npm Package Compare versions

Comparing version 0.1.0 to 0.1.1

demo-site/yarn.lock

192

dist/index.js

@@ -1,1 +0,191 @@

!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):"object"==typeof exports?exports["react-nested-validation"]=t(require("react")):e["react-nested-validation"]=t(e.react)}(window,function(e){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var a=t[n]={i:n,l:!1,exports:{}};return e[n].call(a.exports,a,a.exports,r),a.l=!0,a.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:n})},r.r=function(e){Object.defineProperty(e,"__esModule",{value:!0})},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=0)}({0:function(e,t,r){e.exports=r("tjUo")},Al62:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.isNil=function(e){return void 0===e||null===e||""===e},t.isFunc=function(e){return"function"==typeof e},t.capitalize=function(e){return""+e[0].toUpperCase()+e.slice(1)}},"D+7e":function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n,a=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),o=r("pR90"),i=(n=o)&&n.__esModule?n:{default:n};var u=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.errors=i.default.normalizeErrors()}return a(e,[{key:"addFieldError",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:i.default.ERROR,n=this.errors.fields[e]||[];n.push({type:r,message:t}),this.errors.fields[e]=n,this.updateCounts(r)}},{key:"addFormError",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i.default.ERROR,r=this.errors.form||[];r.push({type:t,message:e}),this.errors.form=r,this.updateCounts(t)}},{key:"updateCounts",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;this.errors.counts[e]=(this.errors.counts[e]||0)+t}}]),e}();t.default=u},JE77:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},a=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),o=s(r("cDcd")),i=r("Al62"),u=s(r("yK9j"));function s(e){return e&&e.__esModule?e:{default:e}}function l(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function f(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}t.default=function(e){return function(t){var r,s,c,d=e.initialPage,v=function(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}(e,["initialPage"]);return(0,u.default)(v)((c=s=function(e){function r(){var e,t,a;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,r);for(var o=arguments.length,u=Array(o),s=0;s<o;s++)u[s]=arguments[s];return t=a=f(this,(e=r.__proto__||Object.getPrototypeOf(r)).call.apply(e,[this].concat(u))),a.state={page:(0,i.isFunc)(d)?d(a.props):d,history:[],visited:{}},a.nextPage=function(e,t){var r=a.props.onChange,o=a.state,u=o.page,s=o.visited;e&&e.validate(!0);var f=!s[u];e&&(e.state.errors.counts.error>0||e.state.errors.counts.warning>0&&f)?(r(u,e.state),a.setState({visited:n({},s,l({},u,!0))})):(0,i.isFunc)(t)?t():a.setState({page:t,visited:n({},s,l({},u,!0)),history:[].concat(function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}(a.state.history),[u])})},a.previousPage=function(){var e=a.state.history;e.length>0&&a.setState({page:e[e.length-1],history:e.slice(0,e.length-1)})},a.renderPage=function(e){var t=a.state.page;return e["render"+(0,i.capitalize)(t)]()},f(a,t)}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(r,o.default.Component),a(r,[{key:"render",value:function(){return o.default.createElement(t,n({},this.props,{nextPage:this.nextPage,previousPage:this.previousPage,finishWizard:this.finishWizard,renderPage:this.renderPage}))}}]),r}(),s.Form=e.form,r=c))||r}}},cDcd:function(t,r){t.exports=e},pR90:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n,a,o,i=function(){return function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var r=[],n=!0,a=!1,o=void 0;try{for(var i,u=e[Symbol.iterator]();!(n=(i=u.next()).done)&&(r.push(i.value),!t||r.length!==t);n=!0);}catch(e){a=!0,o=e}finally{try{!n&&u.return&&u.return()}finally{if(a)throw o}}return r}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),l=r("D+7e"),f=(o=l)&&o.__esModule?o:{default:o};function c(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function d(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}var v=(a=n=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.state=e.normalize(t),this.nested={},this.fieldValidators={},this.defaultValues={}}return s(e,[{key:"parse",value:function(e,t){if(Array.isArray(this.nested)){var r=new this.nested[0];e=(e||[]).map(function(e){return r.parse(e,t)})}else if(this.nested){var n=u({},e=e||{}),a=!0,o=!1,s=void 0;try{for(var l,f=Object.entries(this.nested)[Symbol.iterator]();!(a=(l=f.next()).done);a=!0){var c=l.value,d=i(c,2),v=d[0],h=new(0,d[1]);n[v]=h.parse(e[v],t)}}catch(e){o=!0,s=e}finally{try{!a&&f.return&&f.return()}finally{if(o)throw s}}e=n}else e=e||{};return this.state=u({},this.state,{values:e,touched:{}}),this.validate(t),this.state}},{key:"renderValues",value:function(){var e=this.state.values;if(Array.isArray(this.nested)){var t=this.nested[0];e=(e||[]).map(function(e){return new t(e).renderValues()})}else if(this.nested){var r=u({},e=e||{}),n=!0,a=!1,o=void 0;try{for(var s,l=Object.entries(this.nested)[Symbol.iterator]();!(n=(s=l.next()).done);n=!0){var f=s.value,c=i(f,2),d=c[0],v=new(0,c[1])(e[d]);r[d]=v.renderValues()}}catch(e){a=!0,o=e}finally{try{!n&&l.return&&l.return()}finally{if(a)throw o}}e=r}else e=e||{};return e}},{key:"validate",value:function(e){this.forceValidation=e;var t=new f.default,r=this.getValues();if(e){if(Array.isArray(r)){var n=this.nested[0];r=r.map(function(t){var r=new n(t);return r.validate(e),r.state})}else{var a=!0,o=!1,s=void 0;try{for(var l,c=Object.entries(this.nested)[Symbol.iterator]();!(a=(l=c.next()).done);a=!0){var d=l.value,v=i(d,2),h=v[0],p=v[1];if(void 0!==r[h]){var y=new p(r[h]);y.validate(e),r[h]=y.state}}}catch(e){o=!0,s=e}finally{try{!a&&c.return&&c.return()}finally{if(o)throw s}}}this.state=u({},this.state,{values:r})}if(this.validateFields(t),this.validateForm(t),Array.isArray(r)){var b=!0,m=!1,g=void 0;try{for(var O,w=r[Symbol.iterator]();!(b=(O=w.next()).done);b=!0){var _=O.value.errors,j=void 0===_?{}:_,k=!0,x=!1,P=void 0;try{for(var F,A=Object.entries(j.counts||{})[Symbol.iterator]();!(k=(F=A.next()).done);k=!0){var E=F.value,S=i(E,2),R=S[0],V=S[1];t.updateCounts(R,V)}}catch(e){x=!0,P=e}finally{try{!k&&A.return&&A.return()}finally{if(x)throw P}}}}catch(e){m=!0,g=e}finally{try{!b&&w.return&&w.return()}finally{if(m)throw g}}}else{var C=!0,M=!1,T=void 0;try{for(var z,N=Object.keys(this.nested)[Symbol.iterator]();!(C=(z=N.next()).done);C=!0){var W=(r[z.value]||{}).errors,q=void 0===W?{}:W,D=!0,I=!1,U=void 0;try{for(var G,J=Object.entries(q.counts||{})[Symbol.iterator]();!(D=(G=J.next()).done);D=!0){var K=G.value,L=i(K,2),B=L[0],H=L[1];t.updateCounts(B,H)}}catch(e){I=!0,U=e}finally{try{!D&&J.return&&J.return()}finally{if(I)throw U}}}}catch(e){M=!0,T=e}finally{try{!C&&N.return&&N.return()}finally{if(M)throw T}}}this.state=u({},this.state,{errors:t.errors})}},{key:"validateFields",value:function(e){var t=!0,r=!1,n=void 0;try{for(var a,o=this.iterFieldValidators()[Symbol.iterator]();!(t=(a=o.next()).done);t=!0){var u=a.value,s=i(u,2),l=s[0],f=s[1];this.isTouched(l)&&f(e,l,this)}}catch(e){r=!0,n=e}finally{try{!t&&o.return&&o.return()}finally{if(r)throw n}}}},{key:"validateForm",value:function(e){}},{key:"iterFieldValidators",value:regeneratorRuntime.mark(function e(){var t,r,n,a,o,u,s,l,f,c,d,v,h,p,y;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=!0,r=!1,n=void 0,e.prev=3,a=Object.entries(this.fieldValidators)[Symbol.iterator]();case 5:if(t=(o=a.next()).done){e.next=39;break}u=o.value,s=i(u,2),l=s[0],f=s[1],c=!0,d=!1,v=void 0,e.prev=13,h=f[Symbol.iterator]();case 15:if(c=(p=h.next()).done){e.next=22;break}return y=p.value,e.next=19,[l,y];case 19:c=!0,e.next=15;break;case 22:e.next=28;break;case 24:e.prev=24,e.t0=e.catch(13),d=!0,v=e.t0;case 28:e.prev=28,e.prev=29,!c&&h.return&&h.return();case 31:if(e.prev=31,!d){e.next=34;break}throw v;case 34:return e.finish(31);case 35:return e.finish(28);case 36:t=!0,e.next=5;break;case 39:e.next=45;break;case 41:e.prev=41,e.t1=e.catch(3),r=!0,n=e.t1;case 45:e.prev=45,e.prev=46,!t&&a.return&&a.return();case 48:if(e.prev=48,!r){e.next=51;break}throw n;case 51:return e.finish(48);case 52:return e.finish(45);case 53:case"end":return e.stop()}},e,this,[[3,41,45,53],[13,24,28,36],[29,,31,35],[46,,48,52]])})},{key:"updateValue",value:function(t,r){var n=this.getValues(),a=void 0;Array.isArray(n)?(null===t?n=[].concat(d(n),[e.normalize(r)]):(t=parseInt(t))>=0&&t<n.length&&(n=null===r?[].concat(d(n.slice(0,t)),d(n.slice(t+1))):[].concat(d(n.slice(0,t)),[r],d(n.slice(t+1)))),a=this.state.touched):(n=u({},n,c({},t,r)),a=this.updateTouched(t,r,this.state.touched)),this.state=u({},this.state,{values:n,touched:a}),this.state.errors=this.validate()}},{key:"updateTouched",value:function(e,t,r){var n=this.getInitial();return r=this.getTouched(r),u({},r,c({},e,!!((r[e]||!1)|(!!t||n[e]!=t))))}},{key:"isTouched",value:function(e,t){var r=this.lookupForm(e),n=i(r,2),a=n[0],o=n[1];return this.forceValidation&&(a.touched[o]=!0),a.touched[o]||!1}},{key:"getTouched",value:function(e){return this._getState(e,"touched",{})}},{key:"getInitial",value:function(e){return this._getState(e,"initial",{})}},{key:"getValues",value:function(e){return this._getState(e,"values",this.defaultValues)}},{key:"getValue",value:function(e){var t=this.lookupForm(e),r=i(t,2),n=r[0],a=r[1];return e?n.values[a]:n.values}},{key:"lookupForm",value:function(e){var t=this.state;if(e){var r=e.split("."),n=!0,a=!1,o=void 0;try{for(var i,u=r.slice(0,r.length-1)[Symbol.iterator]();!(n=(i=u.next()).done);n=!0){var s=i.value;t=t.values[s]}}catch(e){a=!0,o=e}finally{try{!n&&u.return&&u.return()}finally{if(a)throw o}}e=r[r.length-1]}return[t,e]}},{key:"_getState",value:function(e,t,r){return void 0===e&&(e=this.state[t]||r),e}}]),e}(),n.ERROR="error",n.WARNING="warning",n.normalizeErrors=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return u({fields:{},form:[],counts:{}},e)},n.normalize=function(e){return u({touched:{},errors:v.normalizeErrors(),values:{}},e)},a);t.default=v},qgJu:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.emptyWarning=t.required=void 0;var n,a=r("pR90"),o=(n=a)&&n.__esModule?n:{default:n},i=r("Al62");var u=function(e,t,r,n,a,o){var u=r.getValue(t);(0,i.isNil)(u)&&e.addFieldError(t,function(e,t,r,n){return e instanceof Function?e(t,r):e||n}(n,t,r,o),a)};(t.required=function e(t){return function(r,n,a){return u(r,n,a,t,o.default.ERROR,e.DEFAULT_MESSAGE)}}).DEFAULT_MESSAGE="This field is required.";t.emptyWarning=function(e){return function(t,r,n){return u(t,r,n,e,o.default.WARNING)}}},tjUo:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Form=t.asFormWizard=t.asForm=void 0;var n=r("qgJu");Object.keys(n).forEach(function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return n[e]}})});var a=u(r("yK9j")),o=u(r("JE77")),i=u(r("pR90"));function u(e){return e&&e.__esModule?e:{default:e}}t.asForm=a.default,t.asFormWizard=o.default,t.Form=i.default},yK9j:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},a=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),o=s(r("cDcd")),i=s(r("pR90")),u=r("Al62");function s(e){return e&&e.__esModule?e:{default:e}}t.default=function(e){return function(t){var r,s;return s=r=function(r){function s(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,s);var r=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(s.__proto__||Object.getPrototypeOf(s)).call(this,t));if(r.makeForm=function(t){var n=new(0,e.form)(r.getFormState());return t&&n.validate(!0),n},r.getFormState=function(){var e=r.props.form,t=void 0===e?{}:e;return i.default.normalize(n({},t,{values:r.getFormValues()}))},r.getFormValues=function(){var t=(r.props.form||{}).values;t||(t=(new(0,e.form)).parse(r.props.initial).values);return t},r.handleChange=function(e,t){var n=r.makeForm();n.updateValue(e,t);var a=r.props,o=a.onChange,i=a.formPrefix;o&&!(0,u.isNil)(i)?o(i,n.state):o&&o(n.state,e,t)},r.validate=function(e){var t=r.makeForm().validate();r.setState({errors:t})},!t.form){var a=r.makeForm();t.onChange&&t.onChange(a.state)}return r}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(s,o.default.Component),a(s,[{key:"shouldComponentUpdate",value:function(e){return(e.form||{}).values!=(this.props.form||{}).values||(e.form||{}).errors!=(this.props.form||{}).errors}},{key:"render",value:function(){var e=this.props,r=e.form,a=function(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}(e,["form"]);return(0,u.isNil)(r)&&(r=this.makeForm(this.props.forceValidation).state),o.default.createElement(t,n({},a,{form:r,onChange:this.handleChange}))}}]),s}(),r.Form=e.form,s}}}})});
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["react-nested-validation"] = factory(require("react"));
else
root["react-nested-validation"] = factory(root["react"]);
})(window, function(__WEBPACK_EXTERNAL_MODULE_react__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ({
/***/ "./src/ErrorSet.js":
/*!*************************!*\
!*** ./src/ErrorSet.js ***!
\*************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = undefined;\n\nvar _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"]) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); } }; }();\n\nvar _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nvar _Form = __webpack_require__(/*! ./Form */ \"./src/Form.js\");\n\nvar _Form2 = _interopRequireDefault(_Form);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * Manages tracking of errors during validation.\n */\nvar ErrorSet = function () {\n function ErrorSet() {\n _classCallCheck(this, ErrorSet);\n\n this.errors = _Form2.default.normalizeErrors();\n }\n\n _createClass(ErrorSet, [{\n key: 'addFieldError',\n\n\n /**\n * Add an error to a form field.\n *\n * @param {string} field The field to add an error to.\n * @param {string} message The error message.\n * @param {string} type The type of error.\n */\n value: function addFieldError(field, message) {\n var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _Form2.default.ERROR;\n\n var fieldErrors = this.errors.fields[field] || [];\n fieldErrors.push({ type: type, message: message });\n this.errors.fields[field] = fieldErrors;\n this.updateCounts(type);\n }\n\n /**\n * Add a form level error.\n *\n * @param {string} message The error message.\n * @param {string} type The type of error.\n */\n\n }, {\n key: 'addFormError',\n value: function addFormError(message) {\n var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _Form2.default.ERROR;\n\n var formErrors = this.errors.form || [];\n formErrors.push({ type: type, message: message });\n this.errors.form = formErrors;\n this.updateCounts(type);\n }\n }, {\n key: 'updateCounts',\n value: function updateCounts(type) {\n var count = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;\n\n this.errors.counts[type] = (this.errors.counts[type] || 0) + count;\n }\n }], [{\n key: 'merge',\n value: function merge(a, b) {\n return {\n fields: _extends({}, a.fields, b.fields),\n form: [].concat(_toConsumableArray(a.form), _toConsumableArray(b.form)),\n counts: this._mergeCounts(a.counts, b.counts)\n };\n }\n }, {\n key: '_mergeCounts',\n value: function _mergeCounts(a, b) {\n var newCounts = _extends({}, a);\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = Object.entries(b)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var _ref = _step.value;\n\n var _ref2 = _slicedToArray(_ref, 2);\n\n var type = _ref2[0];\n var value = _ref2[1];\n\n newCounts[type] = (newCounts[type] || 0) + value;\n }\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n\n return newCounts;\n }\n }]);\n\n return ErrorSet;\n}();\n\nexports.default = ErrorSet;\n\n//# sourceURL=webpack://react-nested-validation/./src/ErrorSet.js?");
/***/ }),
/***/ "./src/Form.js":
/*!*********************!*\
!*** ./src/Form.js ***!
\*********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = undefined;\n\nvar _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"]) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); } }; }();\n\nvar _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nvar _class, _temp;\n\nvar _ErrorSet = __webpack_require__(/*! ./ErrorSet */ \"./src/ErrorSet.js\");\n\nvar _ErrorSet2 = _interopRequireDefault(_ErrorSet);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * Base class for creating new forms. A form is responsible for data\n * initialisation and validation. Forms may be used hierarchically, in both\n * objects and lists.\n */\nvar Form = (_temp = _class = function () {\n\n /**\n * Construct a new form object.\n *\n * @param {object} state The form state.\n */\n\n\n /**\n * Ensure an errors object has all standard fields.\n */\n function Form() {\n var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\n _classCallCheck(this, Form);\n\n this.state = Form.normalize(state);\n\n // Define any subforms. Fields can contain references to other forms for\n // directi subforms, but can also refer to an array with a single form type\n // element. This indicates an array of subforms.\n this.nested = {};\n\n // Define validators for each field of the form.\n this.fieldValidators = {};\n\n // The default values to be returned should no other values exist.\n this.defaultValues = {};\n }\n\n /**\n * Reconstruct incoming form values into a hierarchical representation. Forms\n * may have subforms as specified in the `fields` member. When initialising a\n * form it's convenient to specify just the values part of the initial data,\n * not with all the `touched` and `errors` fields. `parse` reorganises the\n * data into normal form.\n *\n * @param {(object|array)} values Initial form data.\n * @param {bool} forceValidation Force initial form validation.\n */\n\n\n /**\n * Ensure a form state object has all standard fields. Form state objects\n * need to have `touched`, `errors`, and `values` fields.\n */\n\n\n _createClass(Form, [{\n key: 'parse',\n value: function parse(values, forceValidation) {\n var _this = this;\n\n var initial = values;\n if (Array.isArray(this.nested)) {\n values = (values || []).map(function (x) {\n var sub = new _this.nested[0]();\n return sub.parse(x, forceValidation);\n });\n values = [].concat(_toConsumableArray(this.state.values || []), _toConsumableArray(values));\n } else {\n if (this.nested) {\n values = values || {};\n var newValues = _extends({}, values);\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = Object.entries(this.nested)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var _ref = _step.value;\n\n var _ref2 = _slicedToArray(_ref, 2);\n\n var fldName = _ref2[0];\n var Sub = _ref2[1];\n\n var sub = new Sub();\n newValues[fldName] = sub.parse(values[fldName], forceValidation);\n }\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n\n values = newValues;\n } else {\n values = values || {};\n }\n values = _extends({}, this.state.values || {}, values);\n }\n this.state = _extends({}, this.state, {\n values: values,\n touched: {},\n initial: initial\n\n // Handle multi-forms. Apply each multi-form to the same state we've\n // just calculated.\n });var _iteratorNormalCompletion2 = true;\n var _didIteratorError2 = false;\n var _iteratorError2 = undefined;\n\n try {\n for (var _iterator2 = (this.multi || [])[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {\n var MultiForm = _step2.value;\n\n this.state = new MultiForm(this.state).parse(values, forceValidation);\n }\n } catch (err) {\n _didIteratorError2 = true;\n _iteratorError2 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion2 && _iterator2.return) {\n _iterator2.return();\n }\n } finally {\n if (_didIteratorError2) {\n throw _iteratorError2;\n }\n }\n }\n\n this.validate(forceValidation);\n return this.state;\n }\n }, {\n key: 'renderValues',\n value: function renderValues(values) {\n if (values === undefined) {\n values = this.state.values;\n }\n if (Array.isArray(this.nested)) {\n var Sub = this.nested[0];\n values = (values || []).map(function (x) {\n return new Sub(x).renderValues();\n });\n } else {\n values = values || {};\n if (this.nested) {\n var newValues = _extends({}, values);\n var _iteratorNormalCompletion3 = true;\n var _didIteratorError3 = false;\n var _iteratorError3 = undefined;\n\n try {\n for (var _iterator3 = Object.entries(this.nested)[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {\n var _ref3 = _step3.value;\n\n var _ref4 = _slicedToArray(_ref3, 2);\n\n var fldName = _ref4[0];\n var _Sub = _ref4[1];\n\n var sub = new _Sub(values[fldName]);\n newValues[fldName] = sub.renderValues();\n }\n } catch (err) {\n _didIteratorError3 = true;\n _iteratorError3 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion3 && _iterator3.return) {\n _iterator3.return();\n }\n } finally {\n if (_didIteratorError3) {\n throw _iteratorError3;\n }\n }\n }\n\n values = newValues;\n }\n if (this.multi) {\n values = values || {};\n var _newValues = _extends({}, values);\n var _iteratorNormalCompletion4 = true;\n var _didIteratorError4 = false;\n var _iteratorError4 = undefined;\n\n try {\n for (var _iterator4 = this.multi[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {\n var Multi = _step4.value;\n\n _newValues = _extends({}, _newValues, new Multi().renderValues(_newValues));\n }\n } catch (err) {\n _didIteratorError4 = true;\n _iteratorError4 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion4 && _iterator4.return) {\n _iterator4.return();\n }\n } finally {\n if (_didIteratorError4) {\n throw _iteratorError4;\n }\n }\n }\n\n values = _newValues;\n } else {\n values = values || {};\n }\n }\n return values;\n }\n }, {\n key: 'validate',\n value: function validate(force) {\n this.forceValidation = force; // isTouched always returns true\n var errorSet = new _ErrorSet2.default();\n\n // If we're forcing validation we need to go over all sub-forms too.\n // Forced validation usually occurs from a parent form, and there's\n // no guarantee any of the subforms will have been validated.\n var values = this.getValues();\n if (force) {\n if (Array.isArray(values)) {\n var SubForm = this.nested[0];\n values = values.map(function (subValue) {\n var sub = new SubForm(subValue);\n sub.validate(force);\n return sub.state;\n });\n } else {\n var _iteratorNormalCompletion5 = true;\n var _didIteratorError5 = false;\n var _iteratorError5 = undefined;\n\n try {\n for (var _iterator5 = Object.entries(this.nested)[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {\n var _ref5 = _step5.value;\n\n var _ref6 = _slicedToArray(_ref5, 2);\n\n var fieldName = _ref6[0];\n var _SubForm = _ref6[1];\n\n if (values[fieldName] !== undefined) {\n var sub = new _SubForm(values[fieldName]);\n sub.validate(force);\n values[fieldName] = sub.state;\n }\n }\n } catch (err) {\n _didIteratorError5 = true;\n _iteratorError5 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion5 && _iterator5.return) {\n _iterator5.return();\n }\n } finally {\n if (_didIteratorError5) {\n throw _iteratorError5;\n }\n }\n }\n }\n this.state = _extends({}, this.state, {\n values: values\n });\n }\n\n // Perform my local validation.\n this.validateFields(errorSet);\n this.validateForm(errorSet);\n\n // Perform any multi-form validation.\n var _iteratorNormalCompletion6 = true;\n var _didIteratorError6 = false;\n var _iteratorError6 = undefined;\n\n try {\n for (var _iterator6 = (this.multi || [])[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {\n var _SubForm2 = _step6.value;\n\n var _sub = new _SubForm2(values);\n _sub.validate(force);\n errorSet.errors = _ErrorSet2.default.merge(errorSet.errors, _sub.state.errors);\n }\n\n // If the form value is an array add up counts from the sub-\n // forms in the array. Otherwise check if any sub-form fields\n // have counts to add.\n } catch (err) {\n _didIteratorError6 = true;\n _iteratorError6 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion6 && _iterator6.return) {\n _iterator6.return();\n }\n } finally {\n if (_didIteratorError6) {\n throw _iteratorError6;\n }\n }\n }\n\n if (Array.isArray(values)) {\n var _iteratorNormalCompletion7 = true;\n var _didIteratorError7 = false;\n var _iteratorError7 = undefined;\n\n try {\n for (var _iterator7 = values[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {\n var _sub2 = _step7.value;\n var _sub2$errors = _sub2.errors,\n errors = _sub2$errors === undefined ? {} : _sub2$errors;\n var _iteratorNormalCompletion8 = true;\n var _didIteratorError8 = false;\n var _iteratorError8 = undefined;\n\n try {\n for (var _iterator8 = Object.entries(errors.counts || {})[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {\n var _ref7 = _step8.value;\n\n var _ref8 = _slicedToArray(_ref7, 2);\n\n var type = _ref8[0];\n var count = _ref8[1];\n\n errorSet.updateCounts(type, count);\n }\n } catch (err) {\n _didIteratorError8 = true;\n _iteratorError8 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion8 && _iterator8.return) {\n _iterator8.return();\n }\n } finally {\n if (_didIteratorError8) {\n throw _iteratorError8;\n }\n }\n }\n }\n } catch (err) {\n _didIteratorError7 = true;\n _iteratorError7 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion7 && _iterator7.return) {\n _iterator7.return();\n }\n } finally {\n if (_didIteratorError7) {\n throw _iteratorError7;\n }\n }\n }\n } else {\n var _iteratorNormalCompletion9 = true;\n var _didIteratorError9 = false;\n var _iteratorError9 = undefined;\n\n try {\n for (var _iterator9 = Object.keys(this.nested)[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {\n var _fieldName = _step9.value;\n\n var _sub3 = values[_fieldName];\n\n var _ref9 = _sub3 || {},\n _ref9$errors = _ref9.errors,\n _errors = _ref9$errors === undefined ? {} : _ref9$errors;\n\n var _iteratorNormalCompletion10 = true;\n var _didIteratorError10 = false;\n var _iteratorError10 = undefined;\n\n try {\n for (var _iterator10 = Object.entries(_errors.counts || {})[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {\n var _ref10 = _step10.value;\n\n var _ref11 = _slicedToArray(_ref10, 2);\n\n var _type = _ref11[0];\n var _count = _ref11[1];\n\n errorSet.updateCounts(_type, _count);\n }\n } catch (err) {\n _didIteratorError10 = true;\n _iteratorError10 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion10 && _iterator10.return) {\n _iterator10.return();\n }\n } finally {\n if (_didIteratorError10) {\n throw _iteratorError10;\n }\n }\n }\n }\n } catch (err) {\n _didIteratorError9 = true;\n _iteratorError9 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion9 && _iterator9.return) {\n _iterator9.return();\n }\n } finally {\n if (_didIteratorError9) {\n throw _iteratorError9;\n }\n }\n }\n }\n\n this.state = _extends({}, this.state, {\n errors: errorSet.errors\n });\n }\n }, {\n key: 'validateFields',\n value: function validateFields(errors) {\n var _iteratorNormalCompletion11 = true;\n var _didIteratorError11 = false;\n var _iteratorError11 = undefined;\n\n try {\n for (var _iterator11 = this.iterFieldValidators()[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) {\n var _ref12 = _step11.value;\n\n var _ref13 = _slicedToArray(_ref12, 2);\n\n var fieldName = _ref13[0];\n var fieldValidator = _ref13[1];\n\n if (!this.isTouched(fieldName)) {\n continue;\n }\n fieldValidator(errors, fieldName, this);\n }\n } catch (err) {\n _didIteratorError11 = true;\n _iteratorError11 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion11 && _iterator11.return) {\n _iterator11.return();\n }\n } finally {\n if (_didIteratorError11) {\n throw _iteratorError11;\n }\n }\n }\n }\n }, {\n key: 'validateForm',\n value: function validateForm(errors) {}\n }, {\n key: 'iterFieldValidators',\n value: /*#__PURE__*/regeneratorRuntime.mark(function iterFieldValidators() {\n var _iteratorNormalCompletion12, _didIteratorError12, _iteratorError12, _iterator12, _step12, _ref14, _ref15, fn, fvs, _iteratorNormalCompletion13, _didIteratorError13, _iteratorError13, _iterator13, _step13, fv;\n\n return regeneratorRuntime.wrap(function iterFieldValidators$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n _iteratorNormalCompletion12 = true;\n _didIteratorError12 = false;\n _iteratorError12 = undefined;\n _context.prev = 3;\n _iterator12 = Object.entries(this.fieldValidators)[Symbol.iterator]();\n\n case 5:\n if (_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done) {\n _context.next = 39;\n break;\n }\n\n _ref14 = _step12.value;\n _ref15 = _slicedToArray(_ref14, 2);\n fn = _ref15[0];\n fvs = _ref15[1];\n _iteratorNormalCompletion13 = true;\n _didIteratorError13 = false;\n _iteratorError13 = undefined;\n _context.prev = 13;\n _iterator13 = fvs[Symbol.iterator]();\n\n case 15:\n if (_iteratorNormalCompletion13 = (_step13 = _iterator13.next()).done) {\n _context.next = 22;\n break;\n }\n\n fv = _step13.value;\n _context.next = 19;\n return [fn, fv];\n\n case 19:\n _iteratorNormalCompletion13 = true;\n _context.next = 15;\n break;\n\n case 22:\n _context.next = 28;\n break;\n\n case 24:\n _context.prev = 24;\n _context.t0 = _context['catch'](13);\n _didIteratorError13 = true;\n _iteratorError13 = _context.t0;\n\n case 28:\n _context.prev = 28;\n _context.prev = 29;\n\n if (!_iteratorNormalCompletion13 && _iterator13.return) {\n _iterator13.return();\n }\n\n case 31:\n _context.prev = 31;\n\n if (!_didIteratorError13) {\n _context.next = 34;\n break;\n }\n\n throw _iteratorError13;\n\n case 34:\n return _context.finish(31);\n\n case 35:\n return _context.finish(28);\n\n case 36:\n _iteratorNormalCompletion12 = true;\n _context.next = 5;\n break;\n\n case 39:\n _context.next = 45;\n break;\n\n case 41:\n _context.prev = 41;\n _context.t1 = _context['catch'](3);\n _didIteratorError12 = true;\n _iteratorError12 = _context.t1;\n\n case 45:\n _context.prev = 45;\n _context.prev = 46;\n\n if (!_iteratorNormalCompletion12 && _iterator12.return) {\n _iterator12.return();\n }\n\n case 48:\n _context.prev = 48;\n\n if (!_didIteratorError12) {\n _context.next = 51;\n break;\n }\n\n throw _iteratorError12;\n\n case 51:\n return _context.finish(48);\n\n case 52:\n return _context.finish(45);\n\n case 53:\n case 'end':\n return _context.stop();\n }\n }\n }, iterFieldValidators, this, [[3, 41, 45, 53], [13, 24, 28, 36], [29,, 31, 35], [46,, 48, 52]]);\n })\n }, {\n key: 'updateValue',\n value: function updateValue(name, value) {\n var values = this.getValues();\n var touched = this.state.touched;\n var errors = void 0;\n if (Array.isArray(values)) {\n // TODO: Manage touched when removing an array item.\n var names = void 0;\n if (!Array.isArray(name)) {\n names = [name];\n } else {\n names = name;\n }\n var _iteratorNormalCompletion14 = true;\n var _didIteratorError14 = false;\n var _iteratorError14 = undefined;\n\n try {\n for (var _iterator14 = names[Symbol.iterator](), _step14; !(_iteratorNormalCompletion14 = (_step14 = _iterator14.next()).done); _iteratorNormalCompletion14 = true) {\n var _name = _step14.value;\n\n if (_name === null) {\n values = [].concat(_toConsumableArray(values), [Form.normalize({ values: value })]);\n } else {\n _name = parseInt(_name);\n if (_name >= 0 && _name < values.length) {\n values = [].concat(_toConsumableArray(values.slice(0, _name)), [value], _toConsumableArray(values.slice(_name + 1)));\n }\n }\n }\n } catch (err) {\n _didIteratorError14 = true;\n _iteratorError14 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion14 && _iterator14.return) {\n _iterator14.return();\n }\n } finally {\n if (_didIteratorError14) {\n throw _iteratorError14;\n }\n }\n }\n\n values = values.filter(function (x) {\n return x !== null;\n });\n } else {\n if (name === Form.MULTI) {\n values = _extends({}, values, value.values);\n touched = _extends({}, touched, value.touched || {});\n errors = value.errors;\n } else {\n values = _extends({}, values, _defineProperty({}, name, value));\n touched = this.updateTouched(name, value, this.state.touched);\n }\n }\n this.state = _extends({}, this.state, {\n values: values,\n touched: touched\n });\n this.state.errors = this.validate();\n if (errors) {\n this.state.errors = _ErrorSet2.default.merge(this.state.errors, errors);\n }\n }\n }, {\n key: 'updateTouched',\n value: function updateTouched(name, value, touched) {\n var initial = this.getInitial();\n touched = this.getTouched(touched);\n return _extends({}, touched, _defineProperty({}, name, !!(touched[name] || false || !!value || initial[name] != value)));\n }\n }, {\n key: 'isTouched',\n value: function isTouched(name, touched) {\n var _lookupForm = this.lookupForm(name),\n _lookupForm2 = _slicedToArray(_lookupForm, 2),\n state = _lookupForm2[0],\n last = _lookupForm2[1];\n\n if (this.forceValidation) {\n // One is added to the touched value so that after a forced\n // validation the form doesn't forget about showing the error\n // after future changes.\n state.touched[last] = true;\n }\n return state.touched[last] || false;\n }\n }, {\n key: 'getTouched',\n value: function getTouched(touched) {\n return this._getState(touched, 'touched', {});\n }\n }, {\n key: 'getInitial',\n value: function getInitial(initial) {\n return this._getState(initial, 'initial', {});\n }\n }, {\n key: 'getValues',\n value: function getValues(values) {\n return this._getState(values, 'values', this.defaultValues);\n }\n }, {\n key: 'getValue',\n value: function getValue(name) {\n var _lookupForm3 = this.lookupForm(name),\n _lookupForm4 = _slicedToArray(_lookupForm3, 2),\n state = _lookupForm4[0],\n last = _lookupForm4[1];\n\n return name ? state.values[last] : state.values;\n }\n }, {\n key: 'lookupForm',\n value: function lookupForm(name) {\n var state = this.state;\n if (name) {\n var parts = name.split('.');\n var _iteratorNormalCompletion15 = true;\n var _didIteratorError15 = false;\n var _iteratorError15 = undefined;\n\n try {\n for (var _iterator15 = parts.slice(0, parts.length - 1)[Symbol.iterator](), _step15; !(_iteratorNormalCompletion15 = (_step15 = _iterator15.next()).done); _iteratorNormalCompletion15 = true) {\n var part = _step15.value;\n\n state = state.values[part];\n }\n } catch (err) {\n _didIteratorError15 = true;\n _iteratorError15 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion15 && _iterator15.return) {\n _iterator15.return();\n }\n } finally {\n if (_didIteratorError15) {\n throw _iteratorError15;\n }\n }\n }\n\n name = parts[parts.length - 1];\n }\n return [state, name];\n }\n }, {\n key: '_getState',\n value: function _getState(value, name, fallback) {\n if (value === undefined) {\n value = this.state[name] || fallback;\n }\n return value;\n }\n }]);\n\n return Form;\n}(), _class.ERROR = 'error', _class.WARNING = 'warning', _class.MULTI = '', _class.normalizeErrors = function () {\n var errors = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n return _extends({\n fields: {},\n form: [],\n counts: {}\n }, errors);\n}, _class.normalize = function (value) {\n return _extends({\n touched: {},\n errors: Form.normalizeErrors(),\n values: {}\n }, value);\n}, _temp);\nexports.default = Form;\n\n//# sourceURL=webpack://react-nested-validation/./src/Form.js?");
/***/ }),
/***/ "./src/asForm.js":
/*!***********************!*\
!*** ./src/asForm.js ***!
\***********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nvar _react = __webpack_require__(/*! react */ \"react\");\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _Form2 = __webpack_require__(/*! ./Form */ \"./src/Form.js\");\n\nvar _Form3 = _interopRequireDefault(_Form2);\n\nvar _utils = __webpack_require__(/*! ./utils */ \"./src/utils.js\");\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\n/**\n * HOC to turn a React class into a form.\n */\nexports.default = function () {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n return function (Inner) {\n var _class, _temp;\n\n return _temp = _class = function (_React$Component) {\n _inherits(_class, _React$Component);\n\n function _class(props) {\n _classCallCheck(this, _class);\n\n var _this = _possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).call(this, props));\n\n _this.getFormClass = function () {\n return _this.props.Form || options.form;\n };\n\n _this.makeForm = function (forceValidation) {\n var Form = _this.getFormClass();\n var form = new Form(_this.getFormState());\n if (forceValidation) {\n form.validate(true);\n }\n return form;\n };\n\n _this.getFormState = function () {\n var _this$props$form = _this.props.form,\n form = _this$props$form === undefined ? {} : _this$props$form;\n\n if (!(form || {}).values) {\n var _Form = _this.getFormClass();\n form = new _Form().parse(_this.props.initial);\n }\n return _Form3.default.normalize(_extends({}, form));\n };\n\n _this.handleChange = function (name, value) {\n var form = _this.makeForm();\n form.updateValue(name, value);\n var _this$props = _this.props,\n onChange = _this$props.onChange,\n formPrefix = _this$props.formPrefix;\n\n if (onChange) {\n if (formPrefix === _Form3.default.MULTI || !(0, _utils.isNil)(formPrefix)) {\n onChange(formPrefix, form.state);\n } else {\n onChange(form.state, name, value);\n }\n }\n };\n\n _this.validate = function (force) {\n var errors = _this.makeForm().validate();\n _this.setState({ errors: errors });\n };\n\n if (!props.form) {\n var form = _this.makeForm();\n if (props.onChange) {\n props.onChange(form.state);\n }\n }\n return _this;\n }\n\n // TODO: Deprecate.\n /* getFormValues = () => {\n * const {form} = this.props\n * let values = (form || {}).values\n * if (!values) {\n * let Form = options.form\n * values = new Form().parse(this.props.initial).values\n * }\n * return values\n * } */\n\n _createClass(_class, [{\n key: 'shouldComponentUpdate',\n value: function shouldComponentUpdate(nextProps) {\n return (nextProps.form || {}).values != (this.props.form || {}).values || (nextProps.form || {}).errors != (this.props.form || {}).errors;\n }\n }, {\n key: 'render',\n value: function render() {\n\n // Need to be sure we have at least an object value\n // for form.\n var _props = this.props,\n form = _props.form,\n Form = _props.Form,\n otherProps = _objectWithoutProperties(_props, ['form', 'Form']);\n\n if ((0, _utils.isNil)(form)) {\n form = this.makeForm(this.props.forceValidation).state;\n }\n\n return _react2.default.createElement(Inner, _extends({}, otherProps, {\n form: form,\n onChange: this.handleChange\n }));\n }\n }]);\n\n return _class;\n }(_react2.default.Component), _class.Form = options.form, _temp;\n };\n};\n\n//# sourceURL=webpack://react-nested-validation/./src/asForm.js?");
/***/ }),
/***/ "./src/asFormWizard.js":
/*!*****************************!*\
!*** ./src/asFormWizard.js ***!
\*****************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nvar _react = __webpack_require__(/*! react */ \"react\");\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _utils = __webpack_require__(/*! ./utils */ \"./src/utils.js\");\n\nvar _asForm = __webpack_require__(/*! ./asForm */ \"./src/asForm.js\");\n\nvar _asForm2 = _interopRequireDefault(_asForm);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nfunction _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }\n\n/**\n * HOC to turn a React class into a form.\n */\nexports.default = function (options) {\n return function (Inner) {\n var _dec, _class, _class2, _temp2;\n\n var initialPage = options.initialPage,\n otherOpts = _objectWithoutProperties(options, ['initialPage']);\n\n var Outer = (_dec = (0, _asForm2.default)(otherOpts), _dec(_class = (_temp2 = _class2 = function (_React$Component) {\n _inherits(Outer, _React$Component);\n\n function Outer() {\n var _ref;\n\n var _temp, _this, _ret;\n\n _classCallCheck(this, Outer);\n\n for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Outer.__proto__ || Object.getPrototypeOf(Outer)).call.apply(_ref, [this].concat(args))), _this), _this.state = {\n page: (0, _utils.isFunc)(initialPage) ? initialPage(_this.props) : initialPage,\n history: [],\n visited: {}\n }, _this.nextPage = function (form, next, invalid) {\n var _this$state = _this.state,\n page = _this$state.page,\n visited = _this$state.visited;\n\n if (!!form) {\n form.validate(true);\n }\n var firstTime = !visited[page];\n if (!!form && (form.state.errors.counts.error > 0 || form.state.errors.counts.warning > 0 && firstTime)) {\n if (invalid) {\n invalid(page, form);\n }\n _this.setState({ visited: _extends({}, visited, _defineProperty({}, page, true)) });\n } else if ((0, _utils.isFunc)(next)) {\n next();\n } else {\n _this.setState({\n page: next,\n visited: _extends({}, visited, _defineProperty({}, page, true)),\n history: [].concat(_toConsumableArray(_this.state.history), [page])\n });\n }\n }, _this.previousPage = function () {\n var history = _this.state.history;\n\n if (history.length > 0) {\n _this.setState({\n page: history[history.length - 1],\n history: history.slice(0, history.length - 1)\n });\n }\n }, _this.renderPage = function (component) {\n var page = _this.state.page;\n\n var funcName = 'render' + (0, _utils.capitalize)(page);\n return component[funcName]();\n }, _temp), _possibleConstructorReturn(_this, _ret);\n }\n\n _createClass(Outer, [{\n key: 'render',\n value: function render() {\n return _react2.default.createElement(Inner, _extends({}, this.props, {\n nextPage: this.nextPage,\n previousPage: this.previousPage,\n finishWizard: this.finishWizard,\n renderPage: this.renderPage\n }));\n }\n }]);\n\n return Outer;\n }(_react2.default.Component), _class2.Form = options.form, _temp2)) || _class);\n\n return Outer;\n };\n};\n\n//# sourceURL=webpack://react-nested-validation/./src/asFormWizard.js?");
/***/ }),
/***/ "./src/index.js":
/*!**********************!*\
!*** ./src/index.js ***!
\**********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.Form = exports.asFormWizard = exports.asForm = undefined;\n\nvar _validators = __webpack_require__(/*! ./validators */ \"./src/validators.js\");\n\nObject.keys(_validators).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _validators[key];\n }\n });\n});\n\nvar _asForm2 = __webpack_require__(/*! ./asForm */ \"./src/asForm.js\");\n\nvar _asForm3 = _interopRequireDefault(_asForm2);\n\nvar _asFormWizard2 = __webpack_require__(/*! ./asFormWizard */ \"./src/asFormWizard.js\");\n\nvar _asFormWizard3 = _interopRequireDefault(_asFormWizard2);\n\nvar _Form2 = __webpack_require__(/*! ./Form */ \"./src/Form.js\");\n\nvar _Form3 = _interopRequireDefault(_Form2);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nexports.asForm = _asForm3.default; /* eslint-disable */\n\nexports.asFormWizard = _asFormWizard3.default;\nexports.Form = _Form3.default;\n\n//# sourceURL=webpack://react-nested-validation/./src/index.js?");
/***/ }),
/***/ "./src/utils.js":
/*!**********************!*\
!*** ./src/utils.js ***!
\**********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n/**\n * Check for a \"nil\" value; undefined, null, or an empty string.\n */\nvar isNil = exports.isNil = function isNil(value) {\n return value === undefined || value === null || value === '';\n};\n\nvar isFunc = exports.isFunc = function isFunc(value) {\n return typeof value === 'function';\n};\n\nvar capitalize = exports.capitalize = function capitalize(value) {\n return '' + value[0].toUpperCase() + value.slice(1);\n};\n\n//# sourceURL=webpack://react-nested-validation/./src/utils.js?");
/***/ }),
/***/ "./src/validators.js":
/*!***************************!*\
!*** ./src/validators.js ***!
\***************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.emptyWarning = exports.required = undefined;\n\nvar _Form = __webpack_require__(/*! ./Form */ \"./src/Form.js\");\n\nvar _Form2 = _interopRequireDefault(_Form);\n\nvar _utils = __webpack_require__(/*! ./utils */ \"./src/utils.js\");\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * Helper to create a message for a validation error.\n *\n * @param {(string|function)} message How to get the message.\n * @param {string} fieldName Field name generating the error.\n * @param {Form} form The form the error came from.\n * @param {string} defaultMessage The default message to use.\n */\nvar makeMessage = function makeMessage(message, fieldName, form, defaultMessage) {\n if (message instanceof Function) {\n return message(fieldName, form);\n } else {\n return message || defaultMessage;\n }\n};\n\nvar missing = function missing(errors, fieldName, form, message, type, defaultMessage) {\n var value = form.getValue(fieldName);\n if ((0, _utils.isNil)(value)) {\n errors.addFieldError(fieldName, makeMessage(message, fieldName, form, defaultMessage), type);\n }\n};\n\n/**\n * Validator creator for a required field. Returns a function that may\n * be called to validate a field has a non-nil value; should the check\n * fail an error will be assigned.\n *\n * The provided message may be a string, a function, or nil. A function\n * will be called with the field name and the form. A nil value for the\n * message will use the default message.\n *\n * @param {string} message The error message to display.\n * @returns {func}\n */\nvar required = exports.required = function required(message) {\n return function (errors, fieldName, form) {\n return missing(errors, fieldName, form, message, _Form2.default.ERROR, required.DEFAULT_MESSAGE);\n };\n};\n\nrequired.DEFAULT_MESSAGE = 'This field is required.';\n\n/**\n * Validator creator for an empty field check. Returns a function that may\n * be called to validate a field has a non-nil value; should the check\n * fail a warning will be assigned.\n *\n * The provided message may be a string, or a function. A function\n * will be called with the field name and the form.\n *\n * @param {string} message The error message to display.\n * @returns {func}\n */\nvar emptyWarning = exports.emptyWarning = function emptyWarning(message) {\n return function (errors, fieldName, form) {\n return missing(errors, fieldName, form, message, _Form2.default.WARNING);\n };\n};\n\n//# sourceURL=webpack://react-nested-validation/./src/validators.js?");
/***/ }),
/***/ 0:
/*!*************************!*\
!*** multi ./src/index ***!
\*************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("module.exports = __webpack_require__(/*! ./src/index */\"./src/index.js\");\n\n\n//# sourceURL=webpack://react-nested-validation/multi_./src/index?");
/***/ }),
/***/ "react":
/*!************************!*\
!*** external "react" ***!
\************************/
/*! no static exports found */
/***/ (function(module, exports) {
eval("module.exports = __WEBPACK_EXTERNAL_MODULE_react__;\n\n//# sourceURL=webpack://react-nested-validation/external_%22react%22?");
/***/ })
/******/ });
});

2

package.json
{
"name": "react-nested-validation",
"version": "0.1.0",
"version": "0.1.1",
"description": "A toolkit for performing nested validation of React forms.",

@@ -5,0 +5,0 @@ "esnext": "src/index.js",

@@ -9,3 +9,3 @@ import React from 'react'

*/
export default options => Inner =>
export default (options = {}) => Inner =>
class extends React.Component {

@@ -24,4 +24,8 @@ static Form = options.form

getFormClass = () => {
return this.props.Form || options.form
}
makeForm = forceValidation => {
let Form = options.form
let Form = this.getFormClass()
let form = new Form(this.getFormState())

@@ -35,18 +39,22 @@ if (forceValidation) {

getFormState = () => {
const {form = {}} = this.props
let {form = {}} = this.props
if (!(form || {}).values) {
let Form = this.getFormClass()
form = new Form().parse(this.props.initial)
}
return Form.normalize({
...form,
values: this.getFormValues()
...form
})
}
getFormValues = () => {
const {form} = this.props
let values = (form || {}).values
if (!values) {
let Form = options.form
values = new Form().parse(this.props.initial).values
}
return values
}
// TODO: Deprecate.
/* getFormValues = () => {
* const {form} = this.props
* let values = (form || {}).values
* if (!values) {
* let Form = options.form
* values = new Form().parse(this.props.initial).values
* }
* return values
* } */

@@ -57,8 +65,10 @@ handleChange = (name, value) => {

const {onChange, formPrefix} = this.props
if (onChange && !isNil(formPrefix)) {
onChange(formPrefix, form.state)
if (onChange) {
if (formPrefix === Form.MULTI || !isNil(formPrefix)) {
onChange(formPrefix, form.state)
}
else {
onChange(form.state, name, value)
}
}
else if (onChange) {
onChange(form.state, name, value)
}
}

@@ -82,3 +92,3 @@

// for form.
let {form, ...otherProps} = this.props
let {form, Form, ...otherProps} = this.props
if (isNil(form)) {

@@ -85,0 +95,0 @@ form = this.makeForm(this.props.forceValidation).state

@@ -23,4 +23,3 @@ import React from 'react'

nextPage = (form, next) => {
const {onChange} = this.props
nextPage = (form, next, invalid) => {
const {page, visited} = this.state

@@ -32,3 +31,5 @@ if (!!form) {

if (!!form && (form.state.errors.counts.error > 0 || (form.state.errors.counts.warning > 0 && firstTime))) {
onChange(page, form.state)
if (invalid) {
invalid(page, form)
}
this.setState({visited: {...visited, [page]: true}})

@@ -35,0 +36,0 @@ }

@@ -12,2 +12,16 @@ import Form from './Form'

static merge(a, b) {
return {
fields: {
...a.fields,
...b.fields
},
form: [
...a.form,
...b.form
],
counts: this._mergeCounts(a.counts, b.counts)
}
}
/**

@@ -44,2 +58,10 @@ * Add an error to a form field.

static _mergeCounts(a, b) {
const newCounts = {...a}
for (const [type, value] of Object.entries(b)) {
newCounts[type] = (newCounts[type] || 0) + value
}
return newCounts
}
}

@@ -14,2 +14,4 @@ import ErrorSet from './ErrorSet'

static MULTI = ''
/**

@@ -69,25 +71,46 @@ * Ensure an errors object has all standard fields.

parse(values, forceValidation) {
const initial = values
if (Array.isArray(this.nested)) {
const sub = new this.nested[0]()
values = (values || []).map(x => sub.parse(x, forceValidation))
values = (values || []).map(x => {
const sub = new this.nested[0]()
return sub.parse(x, forceValidation)
})
values = [
...(this.state.values || []),
...values
]
}
else if (this.nested) {
values = values || {}
let newValues = {
else {
if (this.nested) {
values = values || {}
let newValues = {
...values
}
for (const [fldName, Sub] of Object.entries(this.nested)) {
const sub = new Sub()
newValues[fldName] = sub.parse(values[fldName], forceValidation)
}
values = newValues
}
else {
values = values || {}
}
values = {
...(this.state.values || {}),
...values
}
for (const [fldName, Sub] of Object.entries(this.nested)) {
const sub = new Sub()
newValues[fldName] = sub.parse(values[fldName], forceValidation)
}
values = newValues
}
else {
values = values || {}
}
this.state = {
...this.state,
values,
touched: {}
touched: {},
initial
}
// Handle multi-forms. Apply each multi-form to the same state we've
// just calculated.
for (const MultiForm of (this.multi || [])) {
this.state = new MultiForm(this.state).parse(values, forceValidation)
}
this.validate(forceValidation)

@@ -97,4 +120,6 @@ return this.state

renderValues() {
let {values} = this.state
renderValues(values) {
if (values === undefined) {
values = this.state.values
}
if (Array.isArray(this.nested)) {

@@ -104,16 +129,31 @@ const Sub = this.nested[0]

}
else if (this.nested) {
else {
values = values || {}
let newValues = {
...values
if (this.nested) {
let newValues = {
...values
}
for (const [fldName, Sub] of Object.entries(this.nested)) {
const sub = new Sub(values[fldName])
newValues[fldName] = sub.renderValues()
}
values = newValues
}
for (const [fldName, Sub] of Object.entries(this.nested)) {
const sub = new Sub(values[fldName])
newValues[fldName] = sub.renderValues()
if(this.multi) {
values = values || {}
let newValues = {
...values
}
for (const Multi of this.multi) {
newValues = {
...newValues,
...new Multi().renderValues(newValues)
}
}
values = newValues
}
values = newValues
else {
values = values || {}
}
}
else {
values = values || {}
}
return values

@@ -158,2 +198,9 @@ }

// Perform any multi-form validation.
for (const SubForm of this.multi || []) {
const sub = new SubForm(values)
sub.validate(force)
errorSet.errors = ErrorSet.merge(errorSet.errors, sub.state.errors)
}
// If the form value is an array add up counts from the sub-

@@ -208,23 +255,25 @@ // forms in the array. Otherwise check if any sub-form fields

let values = this.getValues()
let touched
let touched = this.state.touched
let errors
if (Array.isArray(values)) {
// TODO: Manage touched when removing an array item.
if (name === null) {
values = [
...values,
Form.normalize(value)
]
let names
if (!Array.isArray(name)) {
names = [name]
}
else {
name = parseInt(name)
if (name >= 0 && name < values.length) {
if (value === null) {
names = name
}
for (let name of names) {
if (name === null) {
values = [
...values,
Form.normalize({values: value})
]
}
else {
name = parseInt(name)
if (name >= 0 && name < values.length) {
values = [
...values.slice(0, name),
...values.slice(name + 1)
]
}
else {
values = [
...values.slice(0, name),
value,

@@ -236,10 +285,23 @@ ...values.slice(name + 1)

}
touched = this.state.touched
values = values.filter(x => x !== null)
}
else {
values = {
...values,
[name]: value
if (name === Form.MULTI) {
values = {
...values,
...value.values
}
touched = {
...touched,
...(value.touched || {})
}
errors = value.errors
}
touched = this.updateTouched(name, value, this.state.touched)
else {
values = {
...values,
[name]: value
}
touched = this.updateTouched(name, value, this.state.touched)
}
}

@@ -252,2 +314,5 @@ this.state = {

this.state.errors = this.validate()
if (errors) {
this.state.errors = ErrorSet.merge(this.state.errors, errors)
}
}

@@ -260,3 +325,3 @@

...touched,
[name]: !!((touched[name] || false) | (!!value || initial[name] != value))
[name]: !!((touched[name] || false) || (!!value || initial[name] != value))
}

@@ -263,0 +328,0 @@ }

import Form from '../src/Form'
import {required} from '../src/validators'

@@ -18,6 +19,37 @@ class SubForm extends Form {

class FormA extends Form {
nested = {
a: ArrayForm
}
}
class FormB extends Form {
nested = {
b: ArrayForm
}
}
class MultiForm extends Form {
multi = [
FormA,
FormB
]
}
class RequiredFieldForm extends Form {
fieldValidators = {
f0: [
required()
]
}
}
export {
SubForm,
ParentForm,
ArrayForm
ArrayForm,
FormA,
FormB,
MultiForm,
RequiredFieldForm
}

@@ -5,3 +5,3 @@ import {expect} from 'code'

import {ArrayForm, ParentForm} from './forms'
import {ArrayForm, ParentForm, RequiredFieldForm} from './forms'

@@ -31,3 +31,3 @@ describe('Form', function() {

let form = new Form()
let result = form.parse(values)
form.parse(values)

@@ -57,3 +57,3 @@ it('sets values on form', function() {

let form = new ParentForm()
let result = form.parse(values)
form.parse(values)

@@ -97,3 +97,3 @@ it('sets first level values on form', function() {

let form = new ArrayForm()
let result = form.parse(values)
form.parse(values)

@@ -119,2 +119,22 @@ it('sets array values on form', function() {

describe('updateValues', function() {
describe('initialised', function() {
let form = new RequiredFieldForm({
values: {
f0: 'v0'
}
})
it('fails validation when cleared', function() {
expect(form.state.values.f0).to.not.be.empty()
form.updateValue('f0', '')
expect(form.state.values.f0).to.be.empty()
expect(form.state.errors.fields.f0).to.not.be.undefined()
})
})
})
})
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc