flutter - 如何针对正则表达式验证 textField 并在颤动中显示错误消息
问题描述
我想实现文本字段的功能,如果有人写完文本字段并将其标记为已完成,或者我们可以说文本字段未聚焦,则文本字段验证其中的输入并显示错误消息,如果它与给定的正则表达式不匹配。我想验证电子邮件格式。当用户输入电子邮件并移动并标记完成时,文本字段会验证电子邮件是否有效。我也希望我的表单按钮只有在每个字段都根据正则表达式时才启用
解决方案
您可以使用 TextFormField 中的验证器
final emailAddressRegex = RegExp(r'^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$');
Form(
key: _formKey,
child: new ListView(
shrinkWrap: true,
children: <Widget>[
TextFormField(
maxLines: 1,
keyboardType: TextInputType.emailAddress,
autofocus: false,
decoration: new InputDecoration(
hintText: 'Email',
icon: new Icon(
Icons.mail,
color: Colors.grey,
)),
validator: (value) => value.isEmpty ? 'Email can\'t be empty' : emailAddressRegex.hasMatch(value) ? null : "Enter a valid email address",
onSaved: (value) => _email = value.trim(),
),
confirmButton(),
]
),
),
Widget confirmButton(){
return Center(
child: ElevatedButton(
child: Text("Confirm"),
onPressed: _formKey.currentState.validate() ? (){
//send data
} : null,
),
);
}
推荐阅读
- jmeter - 如何动态发布请求正文 (xml) 并验证响应 (xml)?
- ansible - Ansible:在剧本执行时在需求文件中安装角色
- r - 水 | R parseSetup 问题
- sql-server - SQL Server 是否共享会话?
- json - Webpack 覆盖 require 的行为
- java - JOOQ 的插入...返回 PostgreSQL 10 和 JOOQ 3.10?
- excel - 如何清除工作表中的所有复选框并更新连接到它们的公式
- github - Github 仓库目录结构
- regex - 在引号之间但在冒号之前查找字符串?
- ios - 类的实例没有在 Swift 中打印它的值