From d20c1c8cd4ac5be9152dff42fc0c97d449ef1776 Mon Sep 17 00:00:00 2001 From: Cheton Wu Date: Mon, 23 Oct 2017 22:48:42 +0800 Subject: [PATCH 1/2] Returns a boolean after validation --- src/hocs/form/index.js | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/hocs/form/index.js b/src/hocs/form/index.js index 322b08d..3aab3c8 100644 --- a/src/hocs/form/index.js +++ b/src/hocs/form/index.js @@ -178,6 +178,12 @@ export default function form (WrappedComponent) { return values; }, {}); + hasErrors = () => Object.keys(this.state.byName).reduce((error, name) => { + return error || this.state.byName[name].reduce((error, id) => { + return error || !!(this.state.byId[id].error); + }, false); + }, false); + validate = (name) => { this.setState(state => ({ byId: { @@ -193,6 +199,8 @@ export default function form (WrappedComponent) { }, {}) } }), this._setErrors); + + return !this.hasErrors(); }; validateAll = () => { @@ -214,6 +222,8 @@ export default function form (WrappedComponent) { }, {}) } }), this._setErrors); + + return !this.hasErrors(); }; showError = (component, error) => { From cebaa6759e49c7f81e15a8a1622e2e307e3c097c Mon Sep 17 00:00:00 2001 From: Cheton Wu Date: Tue, 24 Oct 2017 00:21:38 +0800 Subject: [PATCH 2/2] Use an error-first callback to return a boolean value after validation --- src/hocs/form/index.js | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/src/hocs/form/index.js b/src/hocs/form/index.js index 3aab3c8..eaa5424 100644 --- a/src/hocs/form/index.js +++ b/src/hocs/form/index.js @@ -132,7 +132,7 @@ export default function form (WrappedComponent) { }, this._setErrors); }; - _setErrors = () => { + _setErrors = (callback) => { this.setState(state => { return { byId: Object.keys(state.byId).reduce((byId, id) => { @@ -165,7 +165,7 @@ export default function form (WrappedComponent) { }, {}) }; - }); + }, callback); }; getValues = () => Object.keys(this.state.byName).reduce((values, name) => { @@ -184,7 +184,7 @@ export default function form (WrappedComponent) { }, false); }, false); - validate = (name) => { + validate = (name, callback) => { this.setState(state => ({ byId: { ...state.byId, @@ -198,12 +198,18 @@ export default function form (WrappedComponent) { return byId; }, {}) } - }), this._setErrors); - - return !this.hasErrors(); + }), () => { + this._setErrors(() => { + if (typeof callback !== 'function') { + return; + } + const err = this.hasErrors(); + callback(err); + }); + }); }; - validateAll = () => { + validateAll = (callback) => { this.setState(state => ({ byId: { ...state.byId, @@ -221,9 +227,15 @@ export default function form (WrappedComponent) { return byId; }, {}) } - }), this._setErrors); - - return !this.hasErrors(); + }), () => { + this._setErrors(() => { + if (typeof callback !== 'function') { + return; + } + const err = this.hasErrors(); + callback(err); + }); + }); }; showError = (component, error) => {