Home > Enterprise >  How to make sure textformfield input is a number(positive or negative or double)
How to make sure textformfield input is a number(positive or negative or double)

Time:12-07

Hi im facing the issue when converting user input to a double example when i input -3 i faced with an FormatException (FormatException: Invalid double -). How can i deal with this? Furthermore how can i prevent user from entering 2 - or . ( 3.3.3 or 3- or --3)as this will also cause error with the double.parse(). Thanks in advance!

       TextFormField(
          inputFormatters: [FilteringTextInputFormatter.allow(RegExp('[0-9.-]')),],
          keyboardType: TextInputType.number,
          onChanged:(value) {
            setState(() {
              fieldPointX = double.parse(value);
            });
          },
          decoration: InputDecoration(
            border: OutlineInputBorder(),
            labelText: 'X'
          ),

        ),

CodePudding user response:

try using this regExp in your TextFormField widget

TextFormField(
  keyboardType: const TextInputType.numberWithOptions(
    signed: true,
    decimal: true,
  ),
  inputFormatters: [
    FilteringTextInputFormatter.allow(
        RegExp(r'^-?\d*.?\d*')),
  ],
),
  • Related