From ee1659625cfa7affa8ec873279cca35d3b5cd518 Mon Sep 17 00:00:00 2001 From: Michael Telatynski <7t3chguy@gmail.com> Date: Fri, 13 Mar 2020 17:32:02 +0000 Subject: [PATCH] Add Field validation to TextInputDialog Signed-off-by: Michael Telatynski <7t3chguy@gmail.com> --- .../views/dialogs/TextInputDialog.js | 59 +++++++++++++++---- .../views/directory/NetworkDropdown.js | 30 ++++++++++ src/i18n/strings/en_EN.json | 3 + 3 files changed, 81 insertions(+), 11 deletions(-) diff --git a/src/components/views/dialogs/TextInputDialog.js b/src/components/views/dialogs/TextInputDialog.js index 4b21e8206e..e56e9f2b87 100644 --- a/src/components/views/dialogs/TextInputDialog.js +++ b/src/components/views/dialogs/TextInputDialog.js @@ -18,6 +18,7 @@ import React, {createRef} from 'react'; import createReactClass from 'create-react-class'; import PropTypes from 'prop-types'; import * as sdk from '../../../index'; +import Field from "../elements/Field"; export default createReactClass({ displayName: 'TextInputDialog', @@ -33,6 +34,7 @@ export default createReactClass({ focus: PropTypes.bool, onFinished: PropTypes.func.isRequired, hasCancel: PropTypes.bool, + validator: PropTypes.func, // result of withValidation }, getDefaultProps: function() { @@ -45,25 +47,57 @@ export default createReactClass({ }; }, + getInitialState: function() { + return { + value: this.props.value, + valid: false, + }; + }, + UNSAFE_componentWillMount: function() { - this._textinput = createRef(); + this._field = createRef(); }, componentDidMount: function() { if (this.props.focus) { // Set the cursor at the end of the text input - this._textinput.current.value = this.props.value; + // this._field.current.value = this.props.value; + this._field.current.focus(); } }, - onOk: function() { - this.props.onFinished(true, this._textinput.current.value); + onOk: async function(ev) { + ev.preventDefault(); + if (this.props.validator) { + await this._field.current.validate({ allowEmpty: false }); + + if (!this._field.current.state.valid) { + this._field.current.focus(); + this._field.current.validate({ allowEmpty: false, focused: true }); + return; + } + } + this.props.onFinished(true, this.state.value); }, onCancel: function() { this.props.onFinished(false); }, + onChange: function(ev) { + this.setState({ + value: ev.target.value, + }); + }, + + onValidate: async function(fieldState) { + const result = await this.props.validator(fieldState); + this.setState({ + valid: result.valid, + }); + return result; + }, + render: function() { const BaseDialog = sdk.getComponent('views.dialogs.BaseDialog'); const DialogButtons = sdk.getComponent('views.elements.DialogButtons'); @@ -77,14 +111,17 @@ export default createReactClass({