From ffca8d1329706ee0f373ed30d702bd5635b671c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baptiste=20Copp=C3=A9r=C3=A9?= Date: Thu, 27 Sep 2018 09:38:59 +0200 Subject: [PATCH] Add the ability to focus the first erroneous field after a failed validation --- src/mixin/built-in-components.js | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/mixin/built-in-components.js b/src/mixin/built-in-components.js index dee52719e..6ce5fb77d 100644 --- a/src/mixin/built-in-components.js +++ b/src/mixin/built-in-components.js @@ -1,11 +1,13 @@ // Dependencies import React from 'react'; +import ReactDOM from 'react-dom'; import { changeMode } from 'focus-core/application'; import assign from 'object-assign'; import result from 'lodash/object/result'; import find from 'lodash/collection/find'; import defaultsDeep from 'lodash/object/defaultsDeep'; +import isFunction from 'lodash/lang/isFunction'; // Components import { component as Field } from './field'; @@ -161,7 +163,19 @@ export default { this.clearError(); if (this._validate()) { this.action.save.call(this, this._getEntity()); - } + } else if (this.preventFocusOnValidationFailed !== true) { + for (let inptKey in this.refs) { + const refElt = this.refs[inptKey]; + if (isFunction(refElt.validate) || isFunction(refElt._validate)) { + const validationRes = isFunction(refElt.validate) ? refElt.validate() : refElt._validate(); + if (validationRes !== undefined && validationRes !== true) { + const elementPosition = ReactDOM.findDOMNode(refElt).getBoundingClientRect().top; + window.scrollTo(0, elementPosition + window.scrollY - window.innerHeight/2); + break; + } + } + } + } }; return (