I was testing validation of numbers on my iPhone. Here is my code snippet:
child: new TextFormField(
controller: sales,
keyboardType: TextInputType.numberWithOptions(decimal: true),
decoration: const InputDecoration(
filled: true,
fillColor: CupertinoColors.white,
border: const OutlineInputBorder(),
labelText: ‘Sale amount’,
suffixText: ‘ZAR’,
suffixStyle:
const TextStyle(color: Colors.green)),
maxLines: 1,
validator: (val) {
if (val.isEmpty ) return 'Amount is required';
if (val.contains(",")) {
sales.text = val.replaceAll(new RegExp(r","), ".");
}
if (sales.text.indexOf(".") != sales.lastIndexOf(".")) {
return 'Enter valid amount.';
}
else
return null;
},
),
Now, I'm testing the validation with this number 25,52,85 - this is obviously not a valid number but it is a possibility that is allowed on iPhone's number softkeyboard. (Also interesting to note, on the US iPhone, we have commas on the number softkeyboard instead of fullstop and if one had to store a double, the commas have to be converted into fulstops, which I have done in the validate method in the code above)
Now, when I click "Done" to validate the form, an error results in the log and it tells me that it is an invalid Radix 10 number. In other words, Flutter is telling me that a double cannot exist with two commas / fullstops within it.
So to solve this, I wrote in this piece of code under validate to test if the number contains more than 2 fullstops:
if (sales.text.indexOf(".") != sales.lastIndexOf(".")) {
return 'Enter valid amount.';
}
However, I find this to be cumbersome and was wondering if there was a way to test this more elegantly? How can I validate that a number is a valid number in flutter easily?