我想限制TextFormField只接受以逗号分隔的数字,有时用破折号分隔,但我不希望它们彼此连续,也不希望它们连续使用相同的字符。
例:-
1,3-4,9-11
是正确的1,,3--4,9-11
错了1,-3-4,9-11
错了1-,3-4,9-11
错了限制只使用数字、逗号和破折号:-
FilteringTextInputFormatter(
RegExp("[0-9,-]"),
allow: true
)
但是,它并没有像示例中的错误行为那样限制连续行为。
那么,如何将我的TextFormField限制在示例中表示的正确行为上呢?
谢谢。
更新:对于这个问题,我最终采用了这方法。
发布于 2022-10-04 21:10:11
发布于 2022-10-04 22:47:32
对于上面的问题,我最终将FilteringTextInputFormatter与特定于我的情况的自定义TextInputFormatter结合在一起,所以我在下面添加它,这样如果有人想做同样的事情,他们可以看看这个方法:
class RangeTextInputFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
TextSelection newSelection = newValue.selection;
String truncated = newValue.text;
int oldValueLength = oldValue.text.length;
int newValueLength = newValue.text.length;
// Blocks comma and dash at start.
if ((oldValue.text.isEmpty || oldValue.text == "") &&
(newValue.text[newValueLength - 1] == "," ||
newValue.text[newValueLength - 1] == "-")) {
truncated = oldValue.text;
newSelection = oldValue.selection;
}
// Allows numbers at start.
else if (oldValue.text.isEmpty || oldValue.text == "") {
truncated = newValue.text;
newSelection = newValue.selection;
} else {
// Blocks comma and dash after comma.
if (oldValue.text[oldValueLength - 1] == "," &&
(newValue.text[newValueLength - 1] == "," ||
newValue.text[newValueLength - 1] == "-")) {
truncated = oldValue.text;
newSelection = oldValue.selection;
}
// Blocks comma and dash after dash.
else if (oldValue.text[oldValueLength - 1] == "-" &&
(newValue.text[newValueLength - 1] == "," ||
newValue.text[newValueLength - 1] == "-")) {
truncated = oldValue.text;
newSelection = oldValue.selection;
}
// Blocks dash after number dash number. Ex: 48-58- <- this last dash is blocked
else if (oldValue.text.lastIndexOf('-') != -1) {
if (!(oldValue.text
.substring(oldValue.text.lastIndexOf('-'))
.contains(",")) &&
newValue.text[newValueLength - 1] == "-") {
truncated = oldValue.text;
newSelection = oldValue.selection;
}
}
}
return TextEditingValue(
text: truncated,
selection: newSelection,
composing: TextRange.empty,
);
}
}
现在就像使用FilteringTextInputFormatter
一样使用它
inputFormatters: [
FilteringTextInputFormatter(RegExp("[0-9,-]"), allow: true),
RangeTextInputFormatter(),
]
https://stackoverflow.com/questions/73953651
复制相似问题