简体   繁体   English

验证错误消息无法正常工作

[英]validation error messages is not working properly flutter

So I want to make error messages on the sign-in page, but the messages are not popping up or not working very well on both email and password error messages.所以我想在登录页面上制作错误消息,但这些消息没有弹出或在电子邮件和密码错误消息上都没有很好地工作。 Whenever I clicked on the "SIGN IN" button that I made it always go to the next page and it was supposed not to do that.每当我点击“登录”按钮时,我总是会转到下一页,但不应该这样做。 Here is my code:这是我的代码:

SIGN IN FORM登录表格

class sign_in_form extends StatefulWidget {
  const sign_in_form({Key? key}) : super(key: key);

  @override
  _sign_in_formState createState() => _sign_in_formState();
}

class _sign_in_formState extends State<sign_in_form> {
  final _formKey = GlobalKey<FormState>();
  String? email;
  String? password;

  final List<String?> errors = [];

  void addError ({String? error}) {
    if (!errors.contains(error)) {
      setState(() {
        errors.add(error);
      });
    }
  }

  void removeError ({String? error}) {
    if (!errors.contains(error)) {
      setState(() {
        errors.remove(error);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        children: <Widget>[
          buildEmailFormField(),
          SizedBox(height: getProportionateScreenHeight(20)),
          buildPasswordFormField(),
          SizedBox(height: getProportionateScreenHeight(20)),
          errors_form(errors: errors),
          SizedBox(height: getProportionateScreenHeight(20)),
          splash_button(
            press: () {
              if (_formKey.currentState!.validate()) {
                _formKey.currentState!.save();
              }
            },
          ),
        ],
      ),
    );
  }
  TextFormField buildEmailFormField() {
    return TextFormField(
      keyboardType: TextInputType.emailAddress,
      onSaved: (newValue) => email = newValue,
      onChanged: (value) {
        if (value.isNotEmpty) {
          removeError(error: "Please Enter your email");
        }
        else if (emailValidatorRegExp.hasMatch(value)) {
          removeError(error: "Please Enter Valid Email");
        }
        return;
      },
      validator: (value) {
        if (value!.isEmpty) {
          addError(error: "Please Enter your email");
          return "";
        }
        else if (!emailValidatorRegExp.hasMatch(value)) {
          addError(error: "Please Enter Valid Email");
          return "";
        }
        return value;
      },
      decoration: const InputDecoration(
        labelText: "Email",
        hintText: "Enter your email",
        floatingLabelBehavior: FloatingLabelBehavior.always,
        suffixIcon: Padding(
          padding: EdgeInsets.fromLTRB(0, 20, 20, 20),
          child: Icon(Icons.email),
        ),
      ),
    );
  }
  TextFormField buildPasswordFormField() {
    return TextFormField(
      obscureText: true,
      onSaved: (newValue) => password = newValue,
      onChanged: (value){
        if (value.isNotEmpty) {
          removeError(error: "Please Enter your password");
        }
        else if (value.length >= 8) {
          removeError(error: "Password is too short");
        }
        return;
      },
      validator: (value){
        if (value!.isEmpty) {
          addError(error: "Please Enter your password");
          return "";
        }
        else if (!emailValidatorRegExp.hasMatch(value)) {
          addError(error: "Password is too short");
          return "";
        }
        return null;
      },
      decoration: const InputDecoration(
        labelText: "Password",
        hintText: "Enter your password",
        floatingLabelBehavior: FloatingLabelBehavior.always,
        suffixIcon: Padding(
          padding: EdgeInsets.fromLTRB(0, 20, 20, 20),
          child: Icon(Icons.lock),
        ),
      ),
    );
  }
}
  

MY ERROR FORM我的错误表

class errors_form extends StatelessWidget {
  const errors_form({Key? key, required this.errors,}) : super(key: key);
  final List<String?> errors;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: List.generate(
          errors.length, (index) => form_error_text(errors: errors[index]!)),
    );
  }
  Row form_error_text ({required String errors}) {
    return Row(
      children: [
        SvgPicture.asset(
          "assets/icons/Error.svg",
          height: getProportionateScreenWidth(14),
          width: getProportionateScreenWidth(14),
        ),
        SizedBox(width: getProportionateScreenWidth(14)),
        Text(errors),
      ],
    );
  }
}

Please refer to below example code of error messages handling请参考以下错误信息处理示例代码

class MainScreen extends StatelessWidget {
  MainScreen({Key key}) : super(key: key);

  final TextEditingController addressController = TextEditingController();
  final FocusNode addressFocus = FocusNode();
  final TextEditingController stateController = TextEditingController();
  final FocusNode stateFocus = FocusNode();
  final _validationKey = GlobalKey<FormState>();

  int validateAddress(String address) {
    String patttern = r'(^[a-zA-Z0-9 ,.-]*$)';
    RegExp regExp = new RegExp(patttern);
    if (address.isEmpty || address.length == 0) {
      return 1;
    } else if (address.length < 10) {
      return 3;
    } else {
      return 0;
    }
  }

  int validateState(String state) {
    String patttern = r'(^[a-zA-Z0-9 ,.-]*$)';
    RegExp regExp = new RegExp(patttern);
    if (state.isEmpty || state.length == 0) {
      return 1;
    } else {
      return 0;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.lightBlue,
        automaticallyImplyLeading: true,
        leading: Icon(
          Icons.arrow_back,
        ),
        title: Text("Example"),
        centerTitle: true,
      ),
      body: Container(
        padding: EdgeInsets.all(15.0),
        child: Column(
          children: [
            Form(
              key: _validationKey,
              child: Column(
                children: [
                  /* State */
                  TextFormField(
                    autovalidateMode: AutovalidateMode.onUserInteraction,
                    /* autovalidate is disabled */
                    controller: stateController,
                    inputFormatters: [
                      FilteringTextInputFormatter.deny(RegExp(r"\s\s")),
                      FilteringTextInputFormatter.deny(RegExp(
                          r'(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])')),
                    ],
                    keyboardType: TextInputType.text,
                    maxLength: 160,
                    onChanged: (val) {},
                    maxLines: 1,
                    validator: (value) {
                      int res = validateAddress(value);
                      if (res == 1) {
                        return "Please enter state";
                      } else {
                        return null;
                      }
                    },
                    focusNode: stateFocus,
                    autofocus: false,
                    decoration: InputDecoration(
                      errorMaxLines: 3,
                      counterText: "",
                      filled: true,
                      fillColor: Colors.white,
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      disabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                        ),
                      ),
                      errorBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(4)),
                          borderSide: BorderSide(
                            width: 1,
                            color: Colors.red,
                          )),
                      focusedErrorBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Colors.red,
                        ),
                      ),
                      hintText: "Enter state" ?? "",
                    ),
                  ),
                  SizedBox(
                    height: 15.0,
                  ),

                  /* Address */
                  TextFormField(
                    autovalidateMode: AutovalidateMode.onUserInteraction,
                    /* autovalidate is disabled */
                    controller: addressController,
                    inputFormatters: [
                      FilteringTextInputFormatter.deny(RegExp(r"\s\s")),
                      FilteringTextInputFormatter.deny(RegExp(
                          r'(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])')),
                    ],
                    keyboardType: TextInputType.text,
                    maxLength: 60,
                    onChanged: (val) {},
                    maxLines: 1,
                    validator: (value) {
                      int res = validateAddress(value);
                      if (res == 1) {
                        return "Please enter address";
                      } else if (res == 3) {
                        return "Please enter minimum 10 characters";
                      } else {
                        return null;
                      }
                    },
                    focusNode: addressFocus,
                    autofocus: false,
                    decoration: InputDecoration(
                      errorMaxLines: 3,
                      counterText: "",
                      filled: true,
                      fillColor: Colors.white,
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      disabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                        ),
                      ),
                      errorBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(4)),
                          borderSide: BorderSide(
                            width: 1,
                            color: Colors.red,
                          )),
                      focusedErrorBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Colors.red,
                        ),
                      ),
                      hintText: "Enter address" ?? "",
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(
              height: 15.0,
            ),
            OutlinedButton(
              onPressed: () {
                _validationKey.currentState.validate();
                if (stateController.text.isEmpty) {
                  stateFocus.requestFocus();
                } else if (addressController.text.isEmpty ||
                    addressController.text.length < 10) {
                  addressFocus.requestFocus();
                }
              },
              child: Text("Validate"),
            )
          ],
        ),
      ),
    );
  }
}


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM