3

I'm trying to get dart to validate a float that my user will enter in my form. I took the guidance from this SO thread (Regular expression for floating point numbers) on Regex expressions for floating point numbers (for eg, 12.830), and tried it in my flutter app.

new TextFormField(
                        controller:  amt_invested,
                        keyboardType: TextInputType.number,
                        inputFormatters: [WhitelistingTextInputFormatter(new RegExp(r'[+-]?([0-9]*[.])?[0-9]+'))],
                        decoration: const InputDecoration(
                            filled: true,
                            fillColor: CupertinoColors.white,
                            border: const OutlineInputBorder(),
                            labelText: 'Amount invested',
                            prefixText: '\R',
                            suffixText: 'ZAR',
                            suffixStyle:
                            const TextStyle(color: Colors.green)),
                        maxLines: 1,
                        validator: (val) => val.isEmpty ? 'Amount is required' : null,
                      ),

However, the regex is preventing me from entering the full-stop in the float, contrary to what the SO thread said. How do I get this to work properly?

enter image description here

Simon
  • 19,658
  • 27
  • 149
  • 217

1 Answers1

3

Scroll down a few lines in the other thread to the section if you want to match 123.

Here, you do want to match 123. as it's a stepping stone on the way to 123.45.

So, change your RegExp to new RegExp(r'^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$'); As you are using a numeric keypad, you could probably dispense with the leading ^ and trailing $

This example

main() {
  RegExp re;

  re = new RegExp(r'[+-]?([0-9]*[.])?[0-9]+');
  print(test(re, '1234'));
  print(test(re, '1234.'));
  print(test(re, '1234.5'));
  print(test(re, '1234a'));
  print(test(re, '1234..'));

  print('---');

  re = new RegExp(r'^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$');
  print(test(re, '1234'));
  print(test(re, '1234.'));
  print(test(re, '1234.5'));
  print(test(re, '1234a'));
  print(test(re, '1234..'));
  print(test(re, '1234 '));
}

outputs

true
false <- this causes your problem
true
false
false
---
true
true
true
false
false
false
Richard Heap
  • 48,344
  • 9
  • 130
  • 112