skip to Main Content

I have two Text Form Fields inside a Form in flutter. I have added validator to give warnings for invalid value. But I want the warnings to hide when the user starts typing again.

How to hide these warnings?Validation in form fields

I thought I could achieve this using onTap or onChanged function, but couldn’t figure out a way to do this.

2

Answers


  1. try making autoValidationMode of your widgets onUserInteraction:

    autovalidateMode:AutovalidateMode.onUserInteraction,
    
    Login or Signup to reply.
  2. TextFormFields have a focusNode property. While the user is editing a TextFormField the FocusNode associated with that field will have input focus. You can query the state of a FocusNode through the hasFocus property of the node.

    So create and pass a FocusNode for each TextFormField, and then query the state of the relevant node in your validator function.

    For example the code for the email TextFormField should look like this:

    final emailNode = FocusNode();
    ...
    
    TextFormField(
      focusNode: emailNode,
      validator: (value) {
        ...
        else if(widget.inputType == InputType.email &&
          !Validation.isValidEmail(value) &&
          !emailNode.hasFocus){
            return 'Please enter a valid email!;
          }
        },
      ),
    

    This way when the user taps the email field and starts entering a new value the email field will have focus, so the last condition in the validator will be false, so the error message will disappear. When the user taps the password field the email field will lose focus, so the !emailNode.hasFocus will be true, and the error message under the email field will reappear, if the value in the email field is not a valid email address.

    P.S. Next time post code instead of a screenshot please.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search