这是一个很常见的需求,不允许开头输空格。
- 封装:
class RegexUtil {
/// 正则匹配第一个输入字符不能为空格
static const String regexFirstNotNull = r'^(\S){1}';
}
class RegexFormatter extends TextInputFormatter {
RegexFormatter({required this.regex});
/// 需要匹配的正则表达
final String regex;
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
if (newValue.text.isEmpty) {
return TextEditingValue.empty;
}
if (!RegExp(regex).hasMatch(newValue.text)) {
return oldValue;
}
return newValue;
}
}
- 使用:
TextField(
inputFormatters: [
RegexFormatter(regex: RegexUtil.regexFirstNotNull),
],
),
网友评论