Skip to content

Instantly share code, notes, and snippets.

@AlexV525
Created March 24, 2023 07:00
Show Gist options
  • Save AlexV525/aab9de2979ab850f1b82953e876d397b to your computer and use it in GitHub Desktop.
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
/// [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