我想限制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限制为示例中所示的正确行为呢?
谢谢。
更新:对于这个问题,我终于采用了这种方法。
如果您想在提交时进行验证,可以将模式写成:
^[0-9]+(?:[,-][0-9]+)*$
Regex演示
如果支持负前瞻,则在键入时验证时,可以排除-
或,
中匹配的2倍。
请注意,这将允许在末尾使用,
或-
:
^(?!.*[,-][,-])[0-9,-]*
Regex演示
对于我上面的问题,我最终将FilteringTextInputFormatter与特定于我的案例的自定义TextInputFormater相结合,所以我在下面添加了它,这样如果有人想做同样的事情,他们可以看看这种方法:
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(),
]