通过TextField组件 输入框inputFormatters属性限制
FilteringTextInputFormatter.allow() (白名单校验),表示只允许输入符合规则的字符 ;
FilteringTextInputFormatter.deny()(黑名单校验),除了规定的字符,其他都可以输入;
LengthLimitingTextInputFormatter (),(长度限制)
常用正则匹配
/// 禁止输入空格
static const String regexNotNull = "[\\s]";
/// 第一个输入字符不能为空格
static const String regexFirstNotNull = r'^(\S){1}';
///仅支持数字
static const String regexOnlyNumber = "[0-9]";
///仅支持字母和数字
static const String regexOnlyNumberText = "[a-zA-Z]|[0-9]";
- 邮箱: (邮箱键盘,禁止输入空格,限制30位)
TextField(
key: emailKey,
keyboardType: TextInputType.emailAddress,
controller: logic.emailController,
inputFormatters: [
LengthLimitingTextInputFormatter(30),
FilteringTextInputFormatter.deny(
RegExp(RegexUtil.regexNotNull),
)
],
onChanged: (value) {
},
),
- 手机号:(手机号键盘,仅支持数字,禁止输入空格)
TextField(
keyboardType: TextInputType.phone,
inputFormatters: [
FilteringTextInputFormatter.allow(
RegExp(RegexUtil.regexOnlyNumber),
),
FilteringTextInputFormatter.deny(
RegExp(RegexUtil.regexNotNull),
)
],
// suffixIcon: assetsImage('icon_contact.webp',
// width: 17.w, height: 17.h),
onChanged: (value) {
logic.basicContactModel?.fancyGentleRice = value;
logic.update();
},
),
- 银行卡:(限制30位,仅支持数字和字母,小写自动转大写)
TextField(
keyboardType: TextInputType.text,
controller: logic.pwdController,
inputFormatters: [
LengthLimitingTextInputFormatter(30),
FilteringTextInputFormatter.allow(
RegExp(RegexUtil.regexOnlyNumberText),
)
],
onChanged: (value) {
///自动转大写
logic.pwdController.value = logic.pwdController.value
.copyWith(text: value.toUpperCase());
logic.update();
},
)
- 首字母不能为空示例2
TextField(
onChanged: (value) {
String str = value.trimLeft();
if (value.isNotEmpty && value[0] == ' ') {
// 如果第一个字符是空格
controller?.text = str;
controller?.value = TextEditingValue(
text: str,
selection: TextSelection.fromPosition(TextPosition(
affinity: TextAffinity.downstream, offset: str.length)));
}
widget.onChanged?.call(str);
)