首页 > 解决方案 > 如何针对正则表达式验证 textField 并在颤动中显示错误消息

问题描述

我想实现文本字段的功能,如果有人写完文本字段并将其标记为已完成,或者我们可以说文本字段未聚焦,则文本字段验证其中的输入并显示错误消息,如果它与给定的正则表达式不匹配。我想验证电子邮件格式。当用户输入电子邮件并移动并标记完成时,文本字段会验证电子邮件是否有效。我也希望我的表单按钮只有在每个字段都根据正则表达式时才启用

标签: flutterdartflutter-layout

解决方案


您可以使用 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,
      ),
    );
}

推荐阅读