Ben H.
Ben H.

Reputation: 53

How to force user to input a minimum of 2 characters in TextField in Flutter?

I want to Build a TextField in Flutter in which the user must type in his name, but I want to force him to input a minimum of 2 characters.

This is my code:

TextField(
                    autofocus: true,
                    textCapitalization: TextCapitalization.words,
                    textAlign: TextAlign.center,
                    decoration: InputDecoration(
                      labelStyle: TextStyle(color: Colors.blue[900]),
                      border: InputBorder.none,
                      hintText: 'VORNAME',
                    ),
                    style: TextStyle(
                        color: Colors.blue[900],
                        fontWeight: FontWeight.w600,
                        fontSize: MediaQuery.of(context).size.width * 0.075),
                    cursorColor: Colors.greenAccent,
                    inputFormatters: <TextInputFormatter>[
                      WhitelistingTextInputFormatter(RegExp("[a-zA-ZÄäÖöÜü]")) //Only Text as input
                    ],
                    onChanged: (value) {
                      userData.forename = value;
                    },
                    onSubmitted: (value) {
                      Navigator.of(context).push(
                          CupertinoPageRoute(builder: (context) => SurName()));
                    }),

How can I achieve this? Thank you in advance!

Ben

Upvotes: 3

Views: 12848

Answers (1)

Haroon Ashraf Awan
Haroon Ashraf Awan

Reputation: 1219

For Text Field Validation use TextFormField instead of TextField. TextFormField needs to be wrapped with Form widget (If there are two ore more textformfields you can wrap their parent widget with form widget).Form widget requires key and autovalidate boolean (it's optional but it's recommended to show message to user when they haven't validated and as soon as they validate message stops showing). We create two variables and assign it to Form.Then we need a validator in which we validate according to our requirements.(If you need to add more validations you can add multiple if conditions.).Finally on field submitted we check if user has validated the form if validated we perform our desired action else we set autovalidate variable to true to perform autovalidation.

  var formKey = GlobalKey<FormState>();
  bool autoValidate = false;


         Form(
              key: formKey,
              autovalidate: autoValidate,
              child: TextFormField(
                validator: (value){
                 return value.length < 2 ? 'Name must be greater than two characters' : null;
                },
                  autofocus: true,
                  textCapitalization: TextCapitalization.words,
                  textAlign: TextAlign.center,
                  decoration: InputDecoration(
                    labelStyle: TextStyle(color: Colors.blue[900]),
                    border: InputBorder.none,
                    hintText: 'VORNAME',
                  ),
                  style: TextStyle(
                      color: Colors.blue[900],
                      fontWeight: FontWeight.w600,
                      fontSize: MediaQuery.of(context).size.width * 0.075),
                  cursorColor: Colors.greenAccent,
                  inputFormatters: <TextInputFormatter>[
                    WhitelistingTextInputFormatter(RegExp("[a-zA-ZÄäÖöÜü]")) //Only Text as input
                  ],
                  onChanged: (value) {
                    userData.forename = value;
                  },
                  onFieldSubmitted: (value){
                    if(formKey.currentState.validate()){
                      Navigator.of(context).push(
                          CupertinoPageRoute(builder: (context) => SurName()));
                    }else{
                      setState(() {
                        autoValidate=true;
                      });
                    }

                  },
                  ),
            ),

Upvotes: 5

Related Questions