Created
March 24, 2023 07:00
-
-
Save AlexV525/aab9de2979ab850f1b82953e876d397b to your computer and use it in GitHub Desktop.
A regular expression input formatter that allows old value instead of clearing them
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// [Author] Alex (https://github.com/AlexV525) | |
/// [Date] 2022/03/14 11:59 | |
import 'packages:flutter/services.dart'; | |
/// A formatter that takes a [RegExp] to match the value. | |
/// | |
/// Currently the formatter only support match the first group. | |
class RegExpFormatter extends TextInputFormatter { | |
RegExpFormatter(this.regExp); | |
final RegExp regExp; | |
@override | |
TextEditingValue formatEditUpdate( | |
TextEditingValue oldValue, | |
TextEditingValue newValue, | |
) { | |
if (newValue.text.isEmpty || | |
!newValue.composing.isCollapsed || | |
!newValue.selection.isCollapsed) { | |
return newValue; | |
} | |
final Iterable<RegExpMatch> matches = regExp.allMatches(newValue.text); | |
if (matches.length == 1 && | |
matches.first.group(0).toString() == newValue.text) { | |
return newValue; | |
} | |
return oldValue; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment