1

I have the problem that I can't get the proper RegExp together. My Goal is to allow up to 3 digits before the comma, and ONLY IF there is a decimal, then 1 digit after the comma. Which RegExp or Regexes do I have to use for this behavior?

Wanted allowed outcomes: 000.0, 00.0, 0.0, 000, 00, 0

thats the current code, but the problem is that here also 4 digits can be placed without a decimal:

inputFormatters: [
  FilteringTextInputFormatter.allow(RegExp(r'^\d{1,3}\.?\d{0,1}')),
],

I already scrolled through these but they are not working for me:

Javascript Regex to allow only 2 digit numbers and 3 digit numbers as comma separated

Javascript regex to match only up to 11 digits, one comma, and 2 digits after it

Jquery allow only float 2 digit before and after dot

Flutter - Regex in TextFormField

Allow only two decimal number in flutter input?

Nuqo
  • 3,793
  • 1
  • 25
  • 37

3 Answers3

2
RegExp(r'^\d{0,3}(\.\d{1})?$')

try this regex

also I think by comma your mean decimal (.) and considering you want 3 digits before decimal and 1 decimal after decimal

TextFormField(
  autoValidateMode: AutoValidateMode.always,
  validator: (value) {
    return RegExp(r'^\d{0,3}(\.\d{1})?$').hasMatch(value) ? null : 'Invalid value';
  },
)
Akshit Ostwal
  • 451
  • 3
  • 14
1

I'm not a regex expert, so I can only suggest you using this helper function:

  bool match(String input) {
    if (input.split('.').length == 1) {
      // if there is no dot in the string
      // returns true if the length is < 4
      return (input.length < 4) ? true : false;
    } else if (input.split('.').length > 1){
      // if there is more than one dot in the string
      return false;
    } else {
      // if there is a dot in the string
      // returns true if there are < 4 digits before the dot and exactly 1 digit 
      // after the dot
      return (input.split('.')[0].length < 4 && input.split('.')[1].length == 1)
          ? true
          : false;
    }
  }
Andrej
  • 2,743
  • 2
  • 11
  • 28
  • how to use this in a custom class extending 'TextInputFormatter' or as a inputFormatter? – Nuqo Nov 22 '20 at 00:04
  • Like BambinoUA did it in his answer, with a validator. PS I edited the code a bit. – Andrej Nov 22 '20 at 10:12
  • Thanks, I ended up using your solution ripped off with my first 'FilteringTextInputFormatter' together. – Nuqo Nov 22 '20 at 12:00
  • No problem, I'm glad I helped you. If you have any more questions regarding this ask me. – Andrej Nov 22 '20 at 13:55
1

Input formatter is not the case here because it formats data visually and your desired formats includes each other. You should use TextFormField and validator property with @Andrej's validator or use RegExp.

TextFormField(
  autoValidateMode: AutoValidateMode.always,
  validator: (value) {
    return RegEx(r'^\d{1,3}(\.\d)?$').hasMatch(value) ? null : 'Invalid value';
  },
)

RegExp is working here.

BambinoUA
  • 6,126
  • 5
  • 35
  • 51