Can anyone say how to validate only single textform individually?

Viewed 44

Can anyone say how to validate only one single textform field among the group of textform fields which is wrapped with form and given FormState key. The below is my profile page screen which will have email and phone number and name fields. When user not verified email or phone number. he can verify that from here. So I need only one particular field validation separately and also combined validation any how formkey is there.

    Form(
                    key: _formKey,
                    child: Column(children: [
                      Stack(
                        children: [
                          InkWell(
                            onTap: () {
                              chooseImagePicker();
                            },
                            child: CircleAvatar(
                              backgroundImage: (_image != null)
                                  ? FileImage(_image)
                                  : (_userImage != null && _userImage != "")
                                      ? NetworkImage(_userImage)
                                      : NetworkImage(
                                          'https://i.pinimg.com/550x/03/db/57/03db57bc63f03f52c0897a4cf99f23d2.jpg'),
                              radius: 75,
                              backgroundColor: Colors.grey,
                            ),
                          ),
                        ],
                      ),
                      SizedBox(height: 20),
                      Material(
                        elevation: 0.0,
                        color: ColorManager.white,
                        borderRadius: BorderRadius.circular(10.0),
                        child: CustomTextField(
                            controller: _fullNameController,
                            label: AppStrings.signup_namefieldlabel,
                            maxLength: 24,
                            keyboardType: TextInputType.visiblePassword,
    
                            // readOnly: _isEditable,
                            autoValidate: _autoValidate,
                            validator: (String txt) =>
                                TextFieldValidation.validateName(txt),
                            inputFormatters: [
                              FilteringTextInputFormatter.allow(RegExp("[a-zA-Z]"))
                            ],
                            onChanged: (val) {
                              changedValues['fullName'] = val;
                              _name = val;
                            }),
                      ),
                      SizedBox(height: 20.0),
                      Material(
                        elevation: 0.0,
                        color: ColorManager.white,
                        borderRadius: BorderRadius.circular(10.0),
                        child: CustomTextField(
                            controller: _emailController,
                            label: AppStrings.signup_emailfieldlabel,
                            autoValidate: _autoValidate,
                            keyboardType: TextInputType.visiblePassword,
                            readOnly: _emailController.text != "" &&
                                    isEmailVerified != 'false'
                                ? true
                                : false,
                            suffix: isEmailVerified == 'false'
                                ? TextButton(
                                    onPressed: () {
                                      sendOTP();
                                    },
                                    child: Text(
                                      'Verify',
                                      style: TextStyle(
                                          fontSize: 14.0,
                                          color: ColorManager.primary),
                                    ))
                                : null,
                            validator: (String txt) =>
                                TextFieldValidation.validateEmail(txt),
                            maxLength: Constants.emailMaxLength,
                            onChanged: (val) {
                              changedValues['email'] = val;
                              _email = val;
                            }),
                      ),
                      SizedBox(height: 20),
                      Material(
                        elevation: 0.0,
                        color: ColorManager.white,
                        borderRadius: BorderRadius.circular(10.0),
                        child: CustomTextField(
                            controller: _mobileNumberController,
                            label: AppStrings.signup_mobilefieldlabel,
                            autoValidate: _autoValidate,
                            keyboardType: TextInputType.number,
                            maxLength: 10,
                            readOnly: _mobileNumberController.text != "" &&
                                    isMobileVerified != 'false'
                                ? true
                                : false,
                            suffix: isMobileVerified == 'false'
                                ? TextButton(
                                    onPressed: () {
                                      sendOTP();
                                    },
                                    child: Text(
                                      'Verify',
                                      style: TextStyle(
                                          fontSize: 14.0,
                                          color: ColorManager.primary),
                                    ))
                                : null,
                            validator: (String txt) =>
                                TextFieldValidation.validateMobileNumber(txt),
                            inputFormatters: [
                              FilteringTextInputFormatter.digitsOnly,
                            ],
                            onChanged: (val) {
                              changedValues['phoneNumber'] = val;
                              _phoneNumber = val;
                            }),
                      ),
1 Answers

You can do like this for every filed that will depend on others part

validator: (value) {
  if (isVerifiedFromX) return null;

  //else handle others verification
  if (value == null || value.isEmpty) {
    return "Cant be empty";
  }
  return null;
},

Once a filed is verified, It will just return null. An example where email is verified from outside

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

  @override
  State<AuthPage> createState() => _AuthPageState();
}

class _AuthPageState extends State<AuthPage> {
  bool isVerifiedFromX = false;
  final _formKey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          //
          ElevatedButton(
              onPressed: () {
                isVerifiedFromX = !isVerifiedFromX;
                setState(() {});
              },
              child: Text("Email verified $isVerifiedFromX")),
          //*
          Form(
            key: _formKey,
            child: Column(
              children: [
                TextFormField(
                  decoration: InputDecoration(hintText: "Name"),
                  validator: (value) {},
                ),
                TextFormField(
                  decoration: InputDecoration(hintText: "Email"),
                  validator: (value) {
                    if (isVerifiedFromX) return null;
                    //else handle others verification

                    if (value == null || value.isEmpty) {
                      return "Cant be empty";
                    }
                    return null;
                  },
                ),
                ElevatedButton(
                  onPressed: () {
                    final isValid = _formKey.currentState?.validate() ?? false;

                    if (isValid) {}
                  },
                  child: Text("validate"),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

Related