美文网首页
Flutter | TextField 禁止开头输入空格(正则)

Flutter | TextField 禁止开头输入空格(正则)

作者: 无夜之星辰 | 来源:发表于2022-02-16 21:58 被阅读0次

这是一个很常见的需求,不允许开头输空格。

  • 封装:
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),
  ],
),

GitHub

https://github.com/CaiWanFeng/flutter-uikit

相关文章

网友评论

      本文标题:Flutter | TextField 禁止开头输入空格(正则)

      本文链接:https://www.haomeiwen.com/subject/vyadlrtx.html