0

I want to ensure valid input on my text field where user can key in simple math expression for numbers up to 2 d.p such as "1.10 + 3.21 x 0.07". I am doing this through the adding regex to the input formatter constructor in the TextField class.

Following the regex example for 2 d.p here, I modified the code for my text field input formatter to include operators:

String dp = (decimalRange != null && decimalRange > 0)
    ? "([.][0-9]{0,$decimalRange}){0,1}"
    : "";
String num = "($dp)|([0-9]{1,4}$dp)";
_exp = new RegExp(
    "^($num){0,1}[-+x/]{0,1}($num){0,1}[-+x/]{0,1}($num){0,1}\$");

I am able to achieve "1.10 + 3.21 x 0.07", however, the user can also type invalid value into the textfield such as "1...10", "1.10 + 3..21". Any advice to improve the Regex above would be greatly appreciated!

  • Note that I also limit the user to key in a maximum of 3 decimal numbers. so "(2d.p)(operator)(2d.p)(operator)(2d.p)is the maximum limit.
RyanNa
  • 119
  • 1
  • 6
  • 1
    [math_expressions](https://pub.dev/packages/math_expressions) package support math expressions. try this. – Zohaib Tariq Feb 18 '21 at 16:26
  • @ZohaibTariq, thanks for helping. Probably phrased my question badly but I want to ensure that the text field inputs are valid with the help of inputFormatters TextField constructor. I'm not sure if the package can help in this area? – RyanNa Feb 18 '21 at 17:29

0 Answers0