diff --git a/sandbox/pages/StatusInputPage.qml b/sandbox/pages/StatusInputPage.qml index 6c16f5aa..16f16996 100644 --- a/sandbox/pages/StatusInputPage.qml +++ b/sandbox/pages/StatusInputPage.qml @@ -102,6 +102,20 @@ Column { ] } + StatusInput { + label: "Input with StatusRegularExpressionValidator" + charLimit: 30 + input.placeholderText: `Must match regex(${validators[0].regularExpression.toString()}) and <= 30 chars` + validationMode: StatusInput.ValidationMode.IgnoreInvalidInput + + validators: [ + StatusRegularExpressionValidator { + regularExpression: /^[0-9A-Za-z_\$-\s]*$/ + errorMessage: "Bad input!" + } + ] + } + StatusInput { label: "Label" input.placeholderText: "Input width component (right side)" diff --git a/src/StatusQ/Controls/StatusInput.qml b/src/StatusQ/Controls/StatusInput.qml index 2fe235d2..87994984 100644 --- a/src/StatusQ/Controls/StatusInput.qml +++ b/src/StatusQ/Controls/StatusInput.qml @@ -44,7 +44,8 @@ Item { enum ValidationMode { OnlyWhenDirty, // validates input only after it has become dirty - Always // validates input even before it has become dirty + Always, // validates input even before it has become dirty + IgnoreInvalidInput // ignore the new content if it doesn't match } property var errors: ({}) @@ -57,7 +58,9 @@ Item { root.errorMessage = "" } + property string _previousText: text function validate() { + if (!statusBaseInput.dirty && validationMode === StatusInput.ValidationMode.OnlyWhenDirty) { return } @@ -87,11 +90,23 @@ Item { if (errors){ let errs = Object.values(errors) if (errs && errs[0]) { + if(validationMode === StatusInput.ValidationMode.IgnoreInvalidInput + && text.length > _previousText.length) { + // Undo the last input + const cursor = statusBaseInput.cursorPosition; + statusBaseInput.text = _previousText; + if (statusBaseInput.cursor > statusBaseInput.text.length) { + statusBaseInput.cursorPosition = statusBaseInput.text.length; + } else { + statusBaseInput.cursorPosition = cursor-1; + } + } errorMessage.text = errs[0].errorMessage || root.errorMessage; } else { errorMessage.text = "" } } + _previousText = text } if (asyncValidators.length && !Object.values(errors).length) { diff --git a/src/StatusQ/Controls/Validators/StatusRegularExpressionValidator.qml b/src/StatusQ/Controls/Validators/StatusRegularExpressionValidator.qml index ec13751f..7017f664 100644 --- a/src/StatusQ/Controls/Validators/StatusRegularExpressionValidator.qml +++ b/src/StatusQ/Controls/Validators/StatusRegularExpressionValidator.qml @@ -50,7 +50,7 @@ StatusValidator { property var regularExpression name: "regex" - errorMessage: "Please enter a valid regular expression." + errorMessage: `Must match regex(${validatorObj.regularExpression.toString()})` validatorObj: RegularExpressionValidator { regularExpression: root.regularExpression } validate: function (value) {