Home > OS >  How to change TextField border color at onChanged (change character) in flutter?
How to change TextField border color at onChanged (change character) in flutter?

Time:01-12

I need to change textfield border color while changing characters based on email or phone validation.

For Example :

  1. When typing an incomplete email at the time border color is set to RED, after completing typing the email at that time border color is set to WHITE.

  2. Set the Red color of the border when textfiled character length is less than 10 at ongoing typing AND set the WHITE color when the character length is rich to 10.

Quick words: change border color while changing character using Getx, Bloc, Provider etc...

CodePudding user response:

I have Try it Normal way, but have try it using BLOC State Management this video on You Tube in my Project its to please refer this Video its very helpful to you

E-mail Validation function

  emailValidation(emailValue) {
    return RegExp(
      r'^[a-zA-Z0-9.!#$%&’* /=?^_`{|}~-] @[a-zA-Z0-9-] (?:\.[a-zA-Z0-9-] )*$',
    ).hasMatch(emailValue);
  }

Your Widget Using TextFormField:

TextFormField(
  autovalidateMode: AutovalidateMode.onUserInteraction,
  validator: (value) => value!.isEmpty
      ? 'Field Not Empty'
      : !emailValidation(value)
          ? 'Enter Valid Email Address'
          : null,
  decoration: const InputDecoration(
    border: OutlineInputBorder(),
    hintText: 'Enter Email Address',
    labelText: 'Email',
  ),
),

Variable Declaration

final text = TextEditingController();
bool validate = false;

Dispose Method:

  void dispose() {
    text.dispose();
    super.dispose();
  }

Your Widget Using TextField:

 TextField(
          onChanged: (value) {
            setState(() {
              text.text.isEmpty || !emailValidation(text.text)
                  ? validate = true
                  : validate = false;
            });
          },
          controller: text,
          decoration: InputDecoration(
            border: const OutlineInputBorder(),
            labelText: 'Enter Email Address',
            errorText: validate ? 'Enter Valid Email' : null,
          ),
        ),
  • Related