Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextFormField validation when focus changes

Tags:

flutter

I am using a form and some TextFormFields. I can validate the user input as below:

final _form = GlobalKey<FormState>();

void saveForm(){

_form.currentState.validate()

}

//saveForm runs when a save button is pressed.

I want to know whether it's possible to run validate function for a TextField when it loses its focus or not.(I don't want to validate the input by clicking a button and instead, I want to run validate function when user changes the TextField.)

like image 579
mrp490 Avatar asked Oct 23 '19 12:10

mrp490


People also ask

How do I validate a text field when focus changes?

To validate a text field when focus changes from one field to the next, you need a FocusNode to detect when focus has been removed and a GlobalKey<FormFieldState> on the TextFormField to tell it to validate. Here is a sample: Thanks for contributing an answer to Stack Overflow!

How to shift the focus between multiple textformfields inside a form?

In Flutter, the user can shift the focus between multiple TextFormFields inside a Form by using the soft keyboard (not by tapping the TextFormFields). This article shows you 2 ways to do so.

How to validate a textformfield in Salesforce?

Validating TextFormField 1 1.Create a Form with a global key.#N#final _formKey = GlobalKey<FormState> (); ... body: Center ( child: Form ( key:... 2 Add a FormField with validation logic#N#TextFormField ( ..... validator: (value) { if (value.isEmpty) { return... 3 Create a button to validate and submit of the Form More ...

How to call API when textfield focus changes?

Hence to remove overhead I want to call API only when the focus is changed. You can attach a focusNode to TextField so whenever focus changes you can make an api call and validate the text. Inside your class try this


1 Answers

I think you just want to add autovalidate: true, in your form so when your focus is change validation is call

 Form(
         key: _formKey,
         autovalidate: true,
         child:/*...*/
    )

Create your form like

  var _formKey = GlobalKey<FormState>();
  bool _autoValidate = false;

  @override
  Widget build(BuildContext context) {
    return Form(
          key: _formKey,
          autovalidate: _autoValidate,
          child: /* ... */
        ),
      ),
    );
  }

when you click on save

void _onSignUpClicked(BuildContext context) {
    if (_formKey.currentState.validate()) {
      Scaffold.of(context).showSnackBar(SnackBar(content: Text("Successfully sign up")));
    } else {
      setState(() {
        _autoValidate = true;
      });
    }
  }
like image 137
Sanjayrajsinh Avatar answered Oct 06 '22 19:10

Sanjayrajsinh