1
votes

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?

3

3 Answers

2
votes
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';
  },
)
1
votes

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;
    }
  }
1
votes

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.