如何在flutter中设置textformfield中最大单词的验证


inputFormatters: [
LengthLimitingTextInputFormatter(50),
],

TextFormField中的上述代码限制了字符长度,而不是单词。我想设置验证,该字段只允许在flutter中添加最多50个单词。

您可以考虑以下方法。

  1. 使用带有验证器的TextFormField
TextFormField(
validator: (text) {
if (text.split(' ').length > max_limit) {
return 'Reached max words';
}
return null;
},
);
  1. 添加一个装饰,如果超过限制,将显示错误
TextField(
controller: _text,
decoration: InputDecoration(
labelText: 'Enter 5 words',
errorText: _validate ? 'You have entered more than 5 words' : null,
),
);

在您的OnChanged((上->根据您的条件更新_validate变量。

我为您创建了一个格式化程序。将这个格式化程序类添加到您的文件中并使用这个

inputFormatters:[长度限制字输入格式化程序(50(,],

class LengthLimitingWordInputFormatter extends TextInputFormatter {
final int maxWordLength;
LengthLimitingWordInputFormatter({required this.maxWordLength});
@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
if (newValue.text.split(" ").length <= maxWordLength) {
return newValue;
} else {
return oldValue;
}
}
}

使用inputFormatters属性。以下代码将限制textFormField的长度为42:

new TextFormField(
inputFormatters: [
new LengthLimitingTextInputFormatter(42),
],
);

我希望它能有所帮助!

最新更新