我正在使用掩码文本输入格式化程序,并且我已经在我的textformfield字段中完成了这种类型的日期掩蔽。但是,当用户输入丢失或不正确的日期时,我希望防止出现这种情况。我正试图创建一个regex。但是,由于在打开页面时,textformfield是空的,所以regex直接检查并出错--我想编写一个适合日期格式的regex。你能帮帮我吗?
MaskTextINputFormatter
manuelDateInputFormatter = MaskTextInputFormatter(
mask: "##/##/####", filter: {"#": RegExp(r'\d+|-|/')}); // not correctTextFormField
inputFormatters: [widget.viewModel.manuelDateInputFormatter!],发布于 2022-08-17 11:58:52
格式化程序的过滤器不是您进行这种日期验证的地方。为用例提供过滤器是可选的。而是查找TextFormField、其他属性(如keyboardType和验证器)。
我从这些例子中复制了一些相关的代码..。
https://pub.dev/packages/mask_text_input_formatter https://pub.dev/packages/mask_text_input_formatter/example
formatter = new MaskTextInputFormatter(
mask: '##/##/####',
filter: { "#": RegExp(r'[0-9]') },
type: MaskAutoCompletionType.lazy
)
validator = (value) {
if (value == null || value.isEmpty) {
return null;
}
final components = value.split("/");
if (components.length == 3) {
final day = int.tryParse(components[0]);
final month = int.tryParse(components[1]);
final year = int.tryParse(components[2]);
if (day != null && month != null && year != null) {
final date = DateTime(year, month, day);
if (date.year == year && date.month == month && date.day == day) {
return null;
}
}
}
return "wrong date";
}
TextFormField(
controller: TextEditingController(),
inputFormatters: [formatter],
autocorrect: false,
keyboardType: TextInputType.phone,
autovalidateMode: AutovalidateMode.always,
validator: validator
)https://stackoverflow.com/questions/73319507
复制相似问题