【问题标题】:Form validation with regEx dosn't work in flutter使用正则表达式进行表单验证在颤动中不起作用
【发布时间】:2019-07-14 12:36:38
【问题描述】:

我正在登录屏幕中工作,我不想为它制作基本的正则表达式。

我正在使用来自 BeautyTextField 的自定义 UI 元素库

这是我的电子邮件和密码输入小部件

  Widget emailInput(){
    return BeautyTextfield(
                validator: (value)=>RegExp(r"^[a-zA-Z0-9.]+@[a-zA-Z0-9]+\.[a-zA-Z]+").hasMatch(email)?"Enter Valid Email":null,
                decoration: InputDecoration(labelText:"Email"),
                cornerRadius: BorderRadius.all(Radius.circular(50)),
                width: double.maxFinite,
                height: 50,
                duration: Duration(milliseconds: 300),
                inputType: TextInputType.emailAddress,
                keyboardType: TextInputType.emailAddress,
                prefixIcon: Icon(Icons.alternate_email),
                placeholder: "Email",
                onSaved: (value)=> email = value,
                fontFamily: "Muli",
            ); }

Widget passwordInput(){
    return BeautyTextfield( 
                    validator: (value)=> value.length == 6 ? "Enter Password of 6 Numbers":null,
                    cornerRadius: BorderRadius.all(Radius.circular(50)),
                    width: double.maxFinite,
                    height: 50,
                    duration: Duration(milliseconds: 300),
                    inputType: TextInputType.text,
                    prefixIcon: Icon(Icons.lock_outline),
                    obscureText: true,
                    placeholder: "Password",
                    onSaved: (value)=> password = value,

                );           
  }

和我的表单小部件:

Widget build(BuildContext context) {
// Build a Form widget using the _formKey created above.
return Form(
  /////////////////////////////////////////////////////////////
  /// Form Body

  key: signINformKey,
  child: 
    Column(
      children: <Widget>[
        emailInput(),
        passwordInput(),
        submitButton(),
        signUpButton(),
      ],
    ),

);}

如果数据与正则表达式匹配,我在按下登录按钮时使用此功能,因此它将重定向到另一个页面,否则它应该显示一个带有消息“登录错误”的小吃栏,但它不起作用并且每次我点击登录按钮时,即使正则表达式不匹配,它也会重定向到另一个页面,因为signINformKey.currentState.validate() 总是返回 true

【问题讨论】:

标签: flutter flutter-layout


【解决方案1】:

实际上,如果字符串满足正则表达式,hasMatch() 函数将返回 true。您为validator 准备的代码始终返回 null,因为电子邮件字符串与正则表达式不匹配,这就是您被定向到下一页而不是显示 Snackbar 的原因。您可以在正则表达式之前添加! this,因为这会反转结果。

代码:

validator: !RegExp(r"^[a-zA-Z0-9.]+@[a-zA-Z0-9]+\.[a-zA-Z]+").hasMatch(email)?"Enter Valid Email":null

【讨论】:

  • 它也 signINformKey.currentState.validate() 只返回 true
  • 好的,我检查了BeautyTextfield 的代码,您将其修改为接受validator,但您忘记将TextField 更改为TextFormField 并分配validator。跨度>
  • 它也不起作用,所以我使用更改将输入字段的值分配给变量并检查这些变量是否匹配......谢谢你 fayeed
【解决方案2】:

使用onChange 将输入字段内的值分配给变量并检查这些变量

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    相关资源
    最近更新 更多