react-nested-validation
Advanced tools
Comparing version 0.0.1 to 0.0.2
@@ -5,4 +5,3 @@ // components.js | ||
import ReactDOM from 'react-dom' | ||
// import {asForm} from 'react-nested-validation' | ||
import {asForm} from '../../src' | ||
import {asForm} from 'react-nested-validation' | ||
@@ -9,0 +8,0 @@ import {MovieForm, PersonForm, PersonListForm, MovieAndActorsForm} from './forms' |
// forms.js | ||
// import Form, {required} from 'react-nested-validation' | ||
import {Form, required} from '../../src' | ||
import {Form, required} from 'react-nested-validation' | ||
@@ -34,2 +33,13 @@ class PersonForm extends Form { | ||
} | ||
validateForm(errorSet) { | ||
console.log(this.isTouched('movie.title')) | ||
console.log(this.getValue('movie.title')) | ||
if (this.isTouched('movie.title') && this.getValue('movie.title') == 'Jaws') { | ||
errorSet.addFormError({ | ||
type: Form.WARNING, | ||
message: 'Good choice!' | ||
}) | ||
} | ||
} | ||
} | ||
@@ -36,0 +46,0 @@ |
@@ -5,4 +5,3 @@ // components.js | ||
import ReactDOM from 'react-dom' | ||
// import {asForm} from 'react-nested-validation' | ||
import {asForm} from '../../src' | ||
import {asForm} from 'react-nested-validation' | ||
@@ -9,0 +8,0 @@ import {MovieForm} from './forms' |
// forms.js | ||
// import Form, {required} from 'react-nested-validation' | ||
import {Form, required} from '../../src' | ||
import {Form, required} from 'react-nested-validation' | ||
@@ -6,0 +5,0 @@ class MovieForm extends Form { |
@@ -5,4 +5,3 @@ // components.js | ||
import ReactDOM from 'react-dom' | ||
// import {asForm} from 'react-nested-validation' | ||
import {asForm} from '../../src' | ||
import {asForm} from 'react-nested-validation' | ||
@@ -9,0 +8,0 @@ import {MovieForm, PersonForm, MovieAndDirectorForm} from './forms' |
// forms.js | ||
// import Form, {required} from 'react-nested-validation' | ||
import {Form, required} from '../../src' | ||
import {Form, required} from 'react-nested-validation' | ||
@@ -6,0 +5,0 @@ class PersonForm extends Form { |
@@ -8,3 +8,4 @@ { | ||
"build": "./node_modules/.bin/webpack", | ||
"watch": "./node_modules/.bin/webpack --watch" | ||
"watch": "./node_modules/.bin/webpack --watch", | ||
"serve": "jekyll serve" | ||
}, | ||
@@ -27,2 +28,5 @@ "repository": { | ||
"dependencies": { | ||
"react": "^16.3.2", | ||
"react-dom": "^16.3.2", | ||
"react-nested-validation": "latest", | ||
"uptick-demo-site": "latest" | ||
@@ -29,0 +33,0 @@ }, |
module.exports = { | ||
entry: ['babel-polyfill', './index.js'], | ||
output: { | ||
path: __dirname + '/dist', | ||
path: __dirname + '/build', | ||
filename: 'index.js' | ||
@@ -6,0 +6,0 @@ }, |
@@ -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 c(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=e.initialPage,f=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)(f)(r=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),f=0;f<o;f++)u[f]=arguments[f];return t=a=c(this,(e=r.__proto__||Object.getPrototypeOf(r)).call.apply(e,[this].concat(u))),a.state={page:(0,i.isFunc)(s)?s(a.props):s,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 c=!s[u];e&&(e.state.errors.counts.error>0||e.state.errors.counts.warning>0&&c)?(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)]()},c(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}())||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"),c=(o=l)&&o.__esModule?o:{default:o};function f(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,c=Object.entries(this.nested)[Symbol.iterator]();!(a=(l=c.next()).done);a=!0){var f=l.value,d=i(f,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&&c.return&&c.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:"validate",value:function(e){this.forceValidation=e;var t=new c.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,f=Object.entries(this.nested)[Symbol.iterator]();!(a=(l=f.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&&f.return&&f.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===_?{}:_,P=!0,k=!1,x=void 0;try{for(var E,F=Object.entries(j.counts||{})[Symbol.iterator]();!(P=(E=F.next()).done);P=!0){var A=E.value,S=i(A,2),R=S[0],C=S[1];t.updateCounts(R,C)}}catch(e){k=!0,x=e}finally{try{!P&&F.return&&F.return()}finally{if(k)throw x}}}}catch(e){m=!0,g=e}finally{try{!b&&w.return&&w.return()}finally{if(m)throw g}}}else{var V=!0,M=!1,T=void 0;try{for(var z,N=Object.keys(this.nested)[Symbol.iterator]();!(V=(z=N.next()).done);V=!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{!V&&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],c=s[1];this.isTouched(l)&&c(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,c,f,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],c=s[1],f=!0,d=!1,v=void 0,e.prev=13,h=c[Symbol.iterator]();case 15:if(f=(p=h.next()).done){e.next=22;break}return y=p.value,e.next=19,[l,y];case 19:f=!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,!f&&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,f({},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,f({},e,!!((r[e]||!1)|(!!t||n[e]!=t))))}},{key:"isTouched",value:function(e,t){return this.forceValidation?(this.state.touched[e]=(this.state.touched[e]||0)+1,!0):((t=this.getTouched(t))[e]||0)>0}},{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.getValues();return e?t[e]:t}},{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){return 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}()}}}})}); | ||
(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 _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 _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 /**\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\n\n _createClass(ErrorSet, [{\n key: 'addFieldError',\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\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 if (Array.isArray(this.nested)) {\n var sub = new this.nested[0]();\n values = (values || []).map(function (x) {\n return sub.parse(x, forceValidation);\n });\n } else 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 this.state = _extends({}, this.state, {\n values: values,\n touched: {}\n });\n this.validate(forceValidation);\n return this.state;\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 _iteratorNormalCompletion2 = true;\n var _didIteratorError2 = false;\n var _iteratorError2 = undefined;\n\n try {\n for (var _iterator2 = Object.entries(this.nested)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {\n var _ref3 = _step2.value;\n\n var _ref4 = _slicedToArray(_ref3, 2);\n\n var fieldName = _ref4[0];\n var _SubForm = _ref4[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 _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.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 // 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 if (Array.isArray(values)) {\n var _iteratorNormalCompletion3 = true;\n var _didIteratorError3 = false;\n var _iteratorError3 = undefined;\n\n try {\n for (var _iterator3 = values[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {\n var _sub2 = _step3.value;\n var _sub2$errors = _sub2.errors,\n errors = _sub2$errors === undefined ? {} : _sub2$errors;\n var _iteratorNormalCompletion4 = true;\n var _didIteratorError4 = false;\n var _iteratorError4 = undefined;\n\n try {\n for (var _iterator4 = Object.entries(errors.counts || {})[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {\n var _ref5 = _step4.value;\n\n var _ref6 = _slicedToArray(_ref5, 2);\n\n var type = _ref6[0];\n var count = _ref6[1];\n\n errorSet.updateCounts(type, count);\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 } 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 } else {\n var _iteratorNormalCompletion5 = true;\n var _didIteratorError5 = false;\n var _iteratorError5 = undefined;\n\n try {\n for (var _iterator5 = Object.keys(this.nested)[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {\n var _fieldName = _step5.value;\n\n var _sub3 = values[_fieldName];\n\n var _ref7 = _sub3 || {},\n _ref7$errors = _ref7.errors,\n _errors = _ref7$errors === undefined ? {} : _ref7$errors;\n\n var _iteratorNormalCompletion6 = true;\n var _didIteratorError6 = false;\n var _iteratorError6 = undefined;\n\n try {\n for (var _iterator6 = Object.entries(_errors.counts || {})[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {\n var _ref8 = _step6.value;\n\n var _ref9 = _slicedToArray(_ref8, 2);\n\n var _type = _ref9[0];\n var _count = _ref9[1];\n\n errorSet.updateCounts(_type, _count);\n }\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 } 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\n this.state = _extends({}, this.state, {\n errors: errorSet.errors\n });\n }\n }, {\n key: 'validateFields',\n value: function validateFields(errors) {\n var _iteratorNormalCompletion7 = true;\n var _didIteratorError7 = false;\n var _iteratorError7 = undefined;\n\n try {\n for (var _iterator7 = this.iterFieldValidators()[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {\n var _ref10 = _step7.value;\n\n var _ref11 = _slicedToArray(_ref10, 2);\n\n var fieldName = _ref11[0];\n var fieldValidator = _ref11[1];\n\n if (!this.isTouched(fieldName)) {\n continue;\n }\n fieldValidator(errors, fieldName, this);\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 }\n }, {\n key: 'validateForm',\n value: function validateForm(errors) {}\n }, {\n key: 'iterFieldValidators',\n value: /*#__PURE__*/regeneratorRuntime.mark(function iterFieldValidators() {\n var _iteratorNormalCompletion8, _didIteratorError8, _iteratorError8, _iterator8, _step8, _ref12, _ref13, fn, fvs, _iteratorNormalCompletion9, _didIteratorError9, _iteratorError9, _iterator9, _step9, fv;\n\n return regeneratorRuntime.wrap(function iterFieldValidators$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n _iteratorNormalCompletion8 = true;\n _didIteratorError8 = false;\n _iteratorError8 = undefined;\n _context.prev = 3;\n _iterator8 = Object.entries(this.fieldValidators)[Symbol.iterator]();\n\n case 5:\n if (_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done) {\n _context.next = 39;\n break;\n }\n\n _ref12 = _step8.value;\n _ref13 = _slicedToArray(_ref12, 2);\n fn = _ref13[0];\n fvs = _ref13[1];\n _iteratorNormalCompletion9 = true;\n _didIteratorError9 = false;\n _iteratorError9 = undefined;\n _context.prev = 13;\n _iterator9 = fvs[Symbol.iterator]();\n\n case 15:\n if (_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done) {\n _context.next = 22;\n break;\n }\n\n fv = _step9.value;\n _context.next = 19;\n return [fn, fv];\n\n case 19:\n _iteratorNormalCompletion9 = 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 _didIteratorError9 = true;\n _iteratorError9 = _context.t0;\n\n case 28:\n _context.prev = 28;\n _context.prev = 29;\n\n if (!_iteratorNormalCompletion9 && _iterator9.return) {\n _iterator9.return();\n }\n\n case 31:\n _context.prev = 31;\n\n if (!_didIteratorError9) {\n _context.next = 34;\n break;\n }\n\n throw _iteratorError9;\n\n case 34:\n return _context.finish(31);\n\n case 35:\n return _context.finish(28);\n\n case 36:\n _iteratorNormalCompletion8 = 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 _didIteratorError8 = true;\n _iteratorError8 = _context.t1;\n\n case 45:\n _context.prev = 45;\n _context.prev = 46;\n\n if (!_iteratorNormalCompletion8 && _iterator8.return) {\n _iterator8.return();\n }\n\n case 48:\n _context.prev = 48;\n\n if (!_didIteratorError8) {\n _context.next = 51;\n break;\n }\n\n throw _iteratorError8;\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 = void 0;\n if (Array.isArray(values)) {\n // TODO: Manage touched when removing an array item.\n if (name === null) {\n values = [].concat(_toConsumableArray(values), [Form.normalize(value)]);\n } else {\n name = parseInt(name);\n if (name >= 0 && name < values.length) {\n if (value === null) {\n values = [].concat(_toConsumableArray(values.slice(0, name)), _toConsumableArray(values.slice(name + 1)));\n } else {\n values = [].concat(_toConsumableArray(values.slice(0, name)), [value], _toConsumableArray(values.slice(name + 1)));\n }\n }\n }\n touched = this.state.touched;\n } else {\n values = _extends({}, values, _defineProperty({}, name, value));\n touched = this.updateTouched(name, value, this.state.touched);\n }\n this.state = _extends({}, this.state, {\n values: values,\n touched: touched\n });\n this.state.errors = this.validate();\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 _iteratorNormalCompletion10 = true;\n var _didIteratorError10 = false;\n var _iteratorError10 = undefined;\n\n try {\n for (var _iterator10 = parts.slice(0, parts.length - 1)[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {\n var part = _step10.value;\n\n state = state.values[part];\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 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.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 (options) {\n return function (Inner) {\n return function (_React$Component) {\n _inherits(_class2, _React$Component);\n\n function _class2(props) {\n _classCallCheck(this, _class2);\n\n var _this = _possibleConstructorReturn(this, (_class2.__proto__ || Object.getPrototypeOf(_class2)).call(this, props));\n\n _this.makeForm = function (forceValidation) {\n var Form = options.form;\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 return _Form3.default.normalize(_extends({}, form, {\n values: _this.getFormValues()\n }));\n };\n\n _this.getFormValues = function () {\n var form = _this.props.form;\n\n var values = (form || {}).values;\n if (!values) {\n var _Form = options.form;\n values = new _Form().parse(_this.props.initial).values;\n }\n return values;\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 && !(0, _utils.isNil)(formPrefix)) {\n onChange(formPrefix, form.state);\n } else if (onChange) {\n onChange(form.state, name, value);\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 _createClass(_class2, [{\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 otherProps = _objectWithoutProperties(_props, ['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 _class2;\n }(_react2.default.Component);\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;\n\n var initialPage = options.initialPage,\n otherOpts = _objectWithoutProperties(options, ['initialPage']);\n\n var Outer = (_dec = (0, _asForm2.default)(otherOpts), _dec(_class = 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) {\n var onChange = _this.props.onChange;\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 onChange(page, form.state);\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)) || _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?"); | ||
/***/ }) | ||
/******/ }); | ||
}); |
{ | ||
"name": "react-nested-validation", | ||
"version": "0.0.1", | ||
"version": "0.0.2", | ||
"description": "A toolkit for performing nested validation of React forms.", | ||
@@ -18,3 +18,5 @@ "esnext": "src/index.js", | ||
"test": "mocha --require babel-polyfill --require babel-core/register -R nyan --recursive tests/*.js", | ||
"test:one": "mocha --require babel-polyfill --require babel-core/register -R nyan" | ||
"test:one": "mocha --require babel-polyfill --require babel-core/register -R nyan", | ||
"demo:first": "git subtree push --prefix demo-site origin gh-pages", | ||
"demo:push": "git push origin `git subtree split --prefix demo-site master`:gh-pages --force" | ||
}, | ||
@@ -21,0 +23,0 @@ "repository": { |
159
README.md
# react-nested-validation | ||
A toolkit for performing nested validation of React forms. | ||
A toolkit for performing nested validation of forms in React. Please find | ||
a [live demo here](https://uptick.github.io/react-nested-validation/). | ||
@@ -23,3 +24,5 @@ ## Rationale | ||
There are three main components: | ||
No components are offered to help render your presentational components. | ||
You are able to render them any way you choose, using any framework. | ||
Three main categories of components are provided: | ||
@@ -34,149 +37,19 @@ * Forms. | ||
the nested structure of your validation. Forms are ES6 classes that | ||
contain links to subforms, and allow for methods to be overidden in | ||
contain links to nested forms, and allow for methods to be overidden in | ||
order to validate both fields and general form errors. | ||
Validator functions are conveniences for performing common validation | ||
operations, e.g. required fields. | ||
operations, e.g. required fields. Presently there are only two prepackaged | ||
validators: `required` and `emptyWarning`. | ||
The React component wrappers are two higher-order components to help | ||
apply `Form`s to your presentational React comonents. | ||
apply `Form`s to your presentational React comonents. They wrap any | ||
other React component, transforming it into a managed form. A single | ||
prop, `form`, is given to the inner component which contains all the | ||
information not just for the current form, but all nested forms too. | ||
## Basic example | ||
## More to come | ||
```javascript | ||
import Form, {required} from 'react-nested-validation' | ||
class MovieForm extends Form { | ||
fieldValidators = { | ||
title: required() | ||
} | ||
} | ||
``` | ||
```javascript | ||
import React from 'react' | ||
import {asForm} from 'react-nested-validation' | ||
@asForm({form: BasicForm}) | ||
class Movie extends React.Component { | ||
render() { | ||
const {form} = this.props | ||
const {values, errors, touched} = form | ||
return ( | ||
<div> | ||
<input | ||
name="title" | ||
value={values.title} | ||
/> | ||
<input | ||
name="year" | ||
value={values.year} | ||
/> | ||
</div> | ||
) | ||
} | ||
} | ||
``` | ||
## Nested example | ||
```javascript | ||
import Form, {required} from 'react-nested-validation' | ||
class DirectorForm extends Form { | ||
fieldValidators = { | ||
name: required() | ||
} | ||
} | ||
class MovieForm extends Form { | ||
fieldValidators = { | ||
title: required() | ||
} | ||
nested = { | ||
director: DirectorForm | ||
} | ||
} | ||
``` | ||
```javascript | ||
import React from 'react' | ||
import {asForm} from 'react-nested-validation' | ||
@asForm({form: SubForm}) | ||
class Sub extends React.Component { | ||
render() { | ||
const {form} = this.props | ||
const {values, errors, touched} = form | ||
// Render your form here. | ||
} | ||
} | ||
@asForm({form: SuperForm}) | ||
class Super extends React.Component { | ||
render() { | ||
const {form} = this.props | ||
const {values, errors, touched} = form | ||
return ( | ||
<div> | ||
<Sub | ||
form={values.sub} | ||
prefix="sub" | ||
/> | ||
</div> | ||
) | ||
} | ||
} | ||
``` | ||
## Array example | ||
```javascript | ||
import Form, {required} from 'react-nested-validation' | ||
class MovieForm extends Form { | ||
fieldValidators = { | ||
title: required() | ||
} | ||
} | ||
class MovieListForm extends Form { | ||
nested = [ | ||
MovieForm | ||
] | ||
} | ||
``` | ||
```javascript | ||
import React from 'react' | ||
import {asForm} from 'react-nested-validation' | ||
@asForm({form: SubForm}) | ||
class Sub extends React.Component { | ||
render() { | ||
const {form} = this.props | ||
const {values, errors, touched} = form | ||
// Render your form here. | ||
} | ||
} | ||
@asForm({form: SuperForm}) | ||
class Super extends React.Component { | ||
render() { | ||
const {form} = this.props | ||
const {values, errors, touched} = form | ||
return ( | ||
<div> | ||
{ | ||
values.map((sub, ii) => ( | ||
<Sub | ||
form={sub} | ||
prefix={ii} | ||
/> | ||
)) | ||
} | ||
</div> | ||
) | ||
} | ||
} | ||
``` | ||
While we're working on improving the design documentation, please | ||
take a look at the [live examples](https://uptick.github.io/react-nested-validation/) | ||
for more of an idea how to get started. |
@@ -234,2 +234,3 @@ import ErrorSet from './ErrorSet' | ||
isTouched(name, touched) { | ||
const [state, last] = this.lookupForm(name) | ||
if (this.forceValidation) { | ||
@@ -239,7 +240,5 @@ // One is added to the touched value so that after a forced | ||
// after future changes. | ||
this.state.touched[name] = (this.state.touched[name] || 0) + 1 | ||
return true | ||
state.touched[last] = true | ||
} | ||
touched = this.getTouched(touched) | ||
return (touched[name] || 0) > 0 | ||
return (state.touched[last] || false) | ||
} | ||
@@ -260,6 +259,18 @@ | ||
getValue(name) { | ||
const values = this.getValues() | ||
return name ? values[name] : values | ||
const [state, last] = this.lookupForm(name) | ||
return name ? state.values[last] : state.values | ||
} | ||
lookupForm(name) { | ||
let state = this.state | ||
if (name) { | ||
const parts = name.split('.') | ||
for (const part of parts.slice(0, parts.length - 1)) { | ||
state = state.values[part] | ||
} | ||
name = parts[parts.length - 1] | ||
} | ||
return [state, name] | ||
} | ||
_getState(value, name, fallback) { | ||
@@ -266,0 +277,0 @@ if (value === undefined) { |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Uses eval
Supply chain riskPackage uses dynamic code execution (e.g., eval()), which is a dangerous practice. This can prevent the code from running in certain environments and increases the risk that the code may contain exploits or malicious behavior.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
1651185
9287
1
35
54
6
10