Home > front end >  Dart flutter TextField to accept only digit and decimal
Dart flutter TextField to accept only digit and decimal

Time:08-20

I have TextFormField and i want to allow only number and 1 "." and also only 2 digit after decimal.

I have set below things :

keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.allow((RegExp("[0-9.0-9]"))) ],

But this one allows me to enter multiple "." and unlimited after decimal.

I want to allow digits and only 1 "." and only 2 digits after "."

How can i do that?

CodePudding user response:

I got it. It should be

 keyboardType: TextInputType.number,
              inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r'^(\d )?\.?\d{0,2}')), FilteringTextInputFormatter.allow(RegExp(r'^\d \.?\d*')) ],
             

CodePudding user response:

You can use the

onChanged : (val) {

// your logic here

} 

eg: -

              TextFormField(
                controller: numberController,
                decoration: const InputDecoration(
                  label: Text(
                    'Enter Number'
                  ),
                ),
                keyboardType: TextInputType.number,
                onChanged: (val){
                  if(val.indexOf('.') != val.lastIndexOf('.')){
                    numberController.text = val.substring(0, val.length -1);
                    showDialog(context: context, builder: (ctx) => AlertDialog(
                      title: const Text('Please enter valid number'),
                      actions: [
                        IconButton(
                            onPressed: (){
                              Navigator.of(context).pop();
                            },
                            icon: const Icon(Icons.close))
                      ],
                    ));

                  }
                },
              ),

to check the values dynamically. You can use, control and change your values and fields there.

or you can use the simplest solution from Alex

  • Related