From 9228d39e7203cfbff185db9de349108e06cbce96 Mon Sep 17 00:00:00 2001 From: bordun Date: Mon, 9 Nov 2020 19:14:53 +0100 Subject: [PATCH] input: tweak fieldValidator implementation --- src/client/widgets/basics/input.js | 34 +++++++++++++++++++++++------- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/src/client/widgets/basics/input.js b/src/client/widgets/basics/input.js index e85955f8..35393efc 100644 --- a/src/client/widgets/basics/input.js +++ b/src/client/widgets/basics/input.js @@ -20,10 +20,13 @@ class Input extends Canvas { }, class_specific: { asYouType: {type: 'boolean', value: false, help: 'Set to `true` to make the input send its value at each keystroke'}, - fieldValidator: {type: 'string|boolean', value: false, help: [ - 'Set to `abc` to make the input reject all characters, except a, b or c', - '`0-9` will only allow integer to be entered', - '`a-z` will only allow lowercase characters']} + fieldValidator: {type: 'string', value: '', help: [ + 'Regular expression: if the submitted value doesn\'t match the regular expression, it will be reset to the last valid value.', + 'If leading and trailing slashes are omitted, they will be added automatically and the flag will be set to "gm"', + 'Examples:', + '- `^[0-9]*$` accepts digits only, any number of them', + '- `/^[a-z\s]{0,10}$/i` accept between 0 and 10 alphabetic characters and spaces (case insensitive)', + ]} } }) @@ -58,9 +61,22 @@ class Input extends Canvas { this.tabKeyBlur = false }) var asYouType = this.getProp('asYouType') - if (this.getProp('fieldValidator')) { - this.fieldValidator = new RegExp('[^'+this.getProp('fieldValidator')+']', 'g') + + if (this.getProp('fieldValidator') !== '') { + var fieldValidator = String(this.getProp('fieldValidator')), + flags = fieldValidator.match(/^\/.*\/.*$/) ? fieldValidator.split('/').pop() : 'gm', + validator = fieldValidator.match(/^\/.*\/.*$/) ? fieldValidator.replace(/^\/(.*)\/.*$/, '$1') : fieldValidator + + if (!validator.match(/^\^.*\$$/)) validator = '^' + validator + '$' + + try { + this.fieldValidator = new RegExp(validator, flags) + } catch(err) { + console.error((this.getProp('id') || this.props.id) + '.' + propName + ':\n') + console.error(err) + } } + this.input.addEventListener('keydown', (e)=>{ if (e.keyCode === 13) this.blur() // enter else if (e.keyCode === 27) this.blur(false) // esc @@ -103,9 +119,11 @@ class Input extends Canvas { inputChange() { - if (this.fieldValidator) { - this.input.value = this.input.value.replace(this.fieldValidator, ''); + if (this.fieldValidator && !this.input.value.match(this.fieldValidator)) { + this.input.value = this.value + return } + this.setValue(this.input.value, {sync:true, send:true}) }