"Password & confirm pass is not same" Validation in flutter with TextEditingController is not Working

Viewed 29

I want to Check First Password & Confirm Password is the same or not if Not Showing the message is not the same. And if it's the same Call the API to Update this Password.

For this, I am applying some Conditions In "If Else" but it's not working Because of TextEditingController.

Here is my code If you can suggest to me some ideas?

enter image description here

2 Answers

use Regex

static const Pattern PASSWORD_VALIDATE_REGEX =
      r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{8,}$';

String passwordPattern = Constants.PASSWORD_VALIDATE_REGEX;
  RegExp passwordRegExp;

passwordRegExp = RegExp(passwordPattern);
        if (value.trim().isEmpty) {
          return AppStrings.CONFIRM_PASSWORD_EMPTY_ERROR;
        } else if (!passwordRegExp.hasMatch(value)) {
          return AppStrings.CONFIRM_PASSWORD_INVALID_ERROR;
        } else if (value != _passwordController.text) {
          return AppStrings.PASSWORD_DIFFERENT_ERROR;
        }
        return null;

Instead of your way you can use Form widget and validator to do this. Try this:

class MyHomePage extends StatefulWidget {
  MyHomePage({
    Key? key,
  }) : super(key: key);

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _formKey = GlobalKey<FormState>();
  TextEditingController passController = TextEditingController();
  TextEditingController confermPassController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: [
          Form(
            key: _formKey,
            child: Column(
              children: [
                TextFormField(
                  controller: passController,
                ),
                TextFormField(
                  controller: confermPassController,
                  validator: (value) {
                    if (passController.text != confermPassController.text) {
                      return 'pass and conferm pass is not the same';
                    }
                    return null;
                  },
                ),
              ],
            ),
          ),
          SizedBox(
            height: 40,
          ),
          InkWell(
            onTap: _formKey.currentState != null &&
                    _formKey.currentState!.validate()
                ? () {
                    //call your api hear;
                  }
                : null,
            child: Text('call Api'),
          ),
        ],
      ),
    );
  }
}

enter image description here

Related