skip to Main Content

I am creating a TextField in flutter, but I want the input to explicitly follow a regex: ^-?d+(.d+)?(-d+)?(e-?d+)?$ (That allows scientific numbers, in which 'e' is used as powers of ten).

When the user enters a character that makes the input not follow the regex, the character will just not be entered and the valid input that was before remains.
How can I achieve that?

I tried: using inputFormatters: [FilteringTextInputFormatter.allow()] and other formatters, but I can only set banned or allowed characters, not a whole regex expression.

I searched: stackoverflow, but all answers just give that certain characters are allowed and some aren’t. I haven’t seen anyone validate input by a whole complex regex.

2

Answers


  1. You can try something like this

    Below is the link to my code you can test the validation there.

    https://zapp.run/edit/flutter-z6606xl6706?split=50&lazy=false&entry=lib/main.dart&file=lib/main.dart

    Login or Signup to reply.
  2. Custom Input Formatter for Regex

    You can extend TextInputFormatter and then override the formatEditUpdate method. Inside this method you can check whether the new value matches your Regex pattern or not. If it does, you allow the update, else you return the previous value.

    My Approach:

    1. Create Custom Input Formatter:

    import 'package:flutter/services.dart';
    
    class RegexInputFormatter implements TextInputFormatter {
      final RegExp _regex;
    
      RegexInputFormatter(this._regex);
    
      @override
      TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) => 
          _regex.hasMatch(newValue.text) ? newValue : oldValue;
    }
    

    2. Use this custom input formatter with your TextField:

    TextField(
      inputFormatters: [
        RegexInputFormatter(RegExp(r'^-?d+(.d+)?(-d+)?(e-?d+)?$')),
      ],
    )
    

    To ensure that if a user enters a character that would make the entire input not fit the Regex pattern, the character won’t be included and the previous correct input will stay as it is.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search