Flutter TextInputFormatter不允许RegEx [英] Flutter TextInputFormatter not allowing RegEx

查看:70
本文介绍了Flutter TextInputFormatter不允许RegEx的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的TextFormField接受类似 ABCDE1234F 的字符串.我在线测试了正则表达式,并且可以正常工作.由于某些原因,当我使用以下代码时,FextFormField不允许任何形式的输入.

I want my TextFormField to accept a string like ABCDE1234F. I tested the regex online and it works. For some reason, the FextFormField doesn't allow any kind of input when I use the following code.

TextFormField(
    inputFormatters: [
        LengthLimitingTextInputFormatter(10),
        FilteringTextInputFormatter.allow(RegExp(r'[A-Z]{5}[0-9]{4}[A-Z]{1}')),
    ],
    validator: (value) {
        if (value.isEmpty) {
        return 'Please enter some text';
        }
        return null;
    },
    decoration: InputDecoration(
        border: InputBorder.none,
        labelText: 'PAN Number',
    ),
)

有效的字符串应包含5个大写字母,后跟4位数字和最后一个大写字母.

A valid string should have 5 uppercase letters, followed by 4 digits and a last uppercase letter.

进行更多操作后,我意识到问题出在 {} 中.当我只允许数字或数字而不用 {} 限制数字时,它就可以工作.但是我似乎不能限制字符数.

Playing around more with it, I realized that the issue is in {}. When I just allow digits or numbers without limiting the number with {}, it works. But I can't limit seem to limit number of characters.

推荐答案

您的正则表达式模式应为

Your regex pattern should be

RegExp(r'([A-Z]{5}[0-9]{4}[A-Z]{1}$)|([A-Z]{5}[0-9]{1,4}$)|[A-Z]{1,5}$')

validator: (value) {
RegExp regExp = new RegExp(r'[A-Z]{5}[0-9]{4}[A-Z]{1}$');
if (value.isEmpty) {
     return 'Please enter some text';
}else if (regExp.hasMatch(value)){
     return "input more."
}
     return null;
},

这篇关于Flutter TextInputFormatter不允许RegEx的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆