Masked text input formatter for flutter.

Overview

mask_text_input_formatter

Version Build Status codecov GitHub license

The package provides TextInputFormatter for TextField and TextFormField which format the input by a given mask.

logo

Example

Check 'example' folder for code sample

example

Usage

  1. Follow the install guide

  2. Import the library:

import 'package:mask_text_input_formatter/mask_text_input_formatter.dart';
  1. Create mask formatter:
var maskFormatter = new MaskTextInputFormatter(mask: '+# (###) ###-##-##', filter: { "#": RegExp(r'[0-9]') });
  1. Set it to text field:
TextField(inputFormatters: [maskFormatter])

Get value

Get masked text:

print(maskFormatter.getMaskedText()); // -> "+0 (123) 456-78-90"

Get unmasked text:

print(maskFormatter.getUnmaskedText()); // -> 01234567890

Change the mask

You can use the updateMask method to change the mask after the formatter was created:

var textEditingController = TextEditingController(text: "12345678");
var maskFormatter = new MaskTextInputFormatter(mask: '####-####', filter: { "#": RegExp(r'[0-9]') });

TextField(controller: textEditingController, inputFormatters: [maskFormatter])  // -> "1234-5678"

textEditingController.value = maskFormatter.updateMask(mask: "##-##-##-##"); // -> "12-34-56-78"
Comments
  • Strange behavior while erasing text

    Strange behavior while erasing text

    I found a strange behavior while trying to erase the text inside a TextFormField or TextField. I tried this on both versions 1.2.1 and 2.0.0-nullsafety.2 and the behavior are the same. What am I missing?

    Demonstration

    Widget and the formatter

    TextField(
      keyboardType: TextInputType.number,
      inputFormatters: [
        MaskTextInputFormatter(
          mask: '0###-###-##-##',
          filter: {
            "#": RegExp(r'[0-9]'),
          },
       ),
     ],
    ),
    

    flutter doctor -v

    [✓] Flutter (Channel stable, 2.0.3, on Mac OS X 10.15.7 19H524 darwin-x64, locale en-TR)
        • Flutter version 2.0.3 at /Users/apple/SDK/flutter
        • Framework revision 4d7946a68d (4 days ago), 2021-03-18 17:24:33 -0700
        • Engine revision 3459eb2436
        • Dart version 2.12.2
    
    [✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
        • Android SDK at /Users/apple/Library/Android/sdk
        • Platform android-30, build-tools 30.0.2
        • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
        • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
        • All Android licenses accepted.
    
    [✓] Xcode - develop for iOS and macOS
        • Xcode at /Applications/Xcode.app/Contents/Developer
        • Xcode 12.4, Build version 12D4e
        • CocoaPods version 1.10.0
    
    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] Android Studio (version 4.1)
        • Android Studio at /Applications/Android Studio.app/Contents
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
        • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
    
    [✓] IntelliJ IDEA Community Edition (version 2020.3)
        • IntelliJ at /Applications/IntelliJ IDEA CE.app
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
    
    [✓] VS Code (version 1.54.3)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.20.0
    
    [✓] Connected device (2 available)
        • MI 6 (mobile) • 16185061 • android-arm64  • Android 9 (API 28)
        • Chrome (web)  • chrome   • web-javascript • Google Chrome 89.0.4389.90
    
    • No issues found!
    
    opened by firatcetiner 32
  • Cleared controller - Mask keeps the former input

    Cleared controller - Mask keeps the former input

    Hi,

    (taking the example from https://pub.dev/packages/mask_text_input_formatter/example, changed the _ExamplePageState):

    class _ExamplePageState extends State<ExamplePage> {
    
      var textEditingController = TextEditingController();
      var maskTextInputFormatter = MaskTextInputFormatter(mask: "#####", filter: { "#": RegExp(r'[0-9]') });
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Column(
            children: <Widget>[
              TextField(
                controller: textEditingController,
                inputFormatters: [maskTextInputFormatter],
              ),
              FlatButton(
                child: Text('Clear'),
                onPressed: () {
                  textEditingController.clear();
                },
              )
            ],
          )
        );
      }
    }
    

    I have a button which clears the TextFieldby clearing the controller. Well, the TextField seems ok, but when I enter new input, the already cleared will be appended: maskedit

    Since, with other input formatters this doesn't happen, I believe there's a problem with the MaskTextInputFormatter. Am I right or do I make a mistake? How can I clear the TextField properly?

    Thanks in advance.

    opened by S-Man42 7
  • I find a bug when i using

    I find a bug when i using

    I a musk for iban number and it works perfectly when entering values ​​but it does not work properly and does not clear when we use backspase The pattern I used is this: ####-####-####-####-####-####

    I test on flutter 2.2 and 2.0

    I have tested both versions 1.2.1 and 2.0.0-nullsafety.2 and 2.2.0 and 2.2.1.

    opened by mahanpyk 6
  • Problem cleaning controller

    Problem cleaning controller

    I discovered a problem when cleaning the controller using the clear or set empty value in the text field of the controller, when trying to fill the textformfield again the field is all filled in and if I remove the formatter from you the problem with the cache disappears.

    opened by andersonmendesdev 6
  • Problem when mask start with a diferrent character

    Problem when mask start with a diferrent character

    I try to use

    var maskFormatter = MaskTextInputFormatter(mask: '(##) #####-####', filter: { '#': RegExp(r'[0-9]') });
    

    and

    TextField(
      controller: controller,
      inputFormatters: [maskFormatter],
    ),
    

    But when I enter the numbers, the first number duplicates image

    opened by akinncar 5
  • Added support for eager autocompletion

    Added support for eager autocompletion

    Added a parameter autoCompletion in the MaskTextInputFormatter with two values:

    • MaskAutoCompletion.lazy: the current behaviour, where unfiltered characters are added once the following filtered character is input. Ex: with the mask "#/#", "1" then "2" output "1" then "1/2"
    • MaskAutoCompletion.eager: the new behaviour, where unfiltered characters are added when the previous filtered character is input. Ex: with the mask "#/#", "1" then "2" output "1/" then "1/2"

    This fixes #44

    opened by jyardin 4
  • Fix issue 41 Backspace not handled correctly

    Fix issue 41 Backspace not handled correctly

    The problem reproduces on some Android devices only and when trying to delete numbers. beforeSelection.end and beforeSelection.start are the same, thats why beforeSelectionLength calculus wrong and was removed wrong symbols. I fixed it by calculating beforeSelectionEnd by difference of length between beforeText and afterText

    opened by KateZakirova 4
  • Курсор  не смещается вперёд

    Курсор не смещается вперёд

    Привет, Сергей!

    flutter doctor -v

    [√] Flutter (Channel master, 1.22.0-10.0.pre.176, on Microsoft Windows [Version 10.0.19041.508], locale ru-RU) • Flutter version 1.22.0-10.0.pre.176 at C:\Users\kasim\Documents\flutter • Framework revision 96ca0e272b (6 hours ago), 2020-09-15 09:02:04 +0100 • Engine revision 7e962ba911 • Dart version 2.10.0 (build 2.10.0-124.0.dev)

    описание проблемы

    Установил на TextFormField маску телефонного номера из примера. Курсор автоматически не смещается вперёд, а при вводе пробела содержимое очищается.

    https://dump.video/i/xmeNBp.mp4

    opened by Dimous 4
  • Support eager formatting

    Support eager formatting

    This is a great plugin. Thank you for simplifying TextInputFormatters.

    One feature request is to have eager formatting

    Given this configuration for date formatting:

    MaskTextInputFormatter(
      mask: '##/##/####',
      filter: <String, RegExp>{'#': RegExp('[0-9]')},
    ),
    

    I would expect that upon entering 01, that the text field would add the formatting so it read 01/. Reason being, if a user was really trying to enter in / after the 01, the text field doesn't allow them to do that, which could be frustrating.

    Is that doable? I think the trickiest bit might be that when using backspace, we wouldn't want to add the / on every text input event, or they'd never be able to delete any of the formatting. So there'd need to be some way to compare the state of the text before/after the change.

    opened by steven-spiel 3
  • Doesn't mask with widget keyboard

    Doesn't mask with widget keyboard

    Hi 😁

    I'm updating the value of TextEditingController from a widget based keyboard (buttons) but I can't get the output to be masked.

    Any suggestion? Please and thank you

    opened by ManuLpz4 3
  • MaskTextInputFormatter erases characters when I do the insertion

    MaskTextInputFormatter erases characters when I do the insertion

    When I insert the number it erases the previous digit. And when a non-number character is inserted it erases all the inserted data.

    ScreenRecording

    I tried using it in a 'vanilla' TextFormField and had the same result.

    TextFormField(
      onChanged: (value) {
        setState(() {
          mobile.setContactNumber(value);
        });
      },
      initialValue:
          mobile.contactNumber,
      inputFormatters: [MaskTextInputFormatter(mask: "+258 ###-##-##")],
    ),
    
    opened by LSambo02 2
  • Bug when using setstate in onChanged

    Bug when using setstate in onChanged

    Currently textfield clears after UI update (setState, for example). I use a timer in my app, which also updates the corresponding text widget that indicates remaining time, and UI updates every second, making input really frustrating, because every second textfield is being cleared, follow the example

    TextField(
                  inputFormatters: [
                    MaskTextInputFormatter(
                      mask: '##/##/####',
                    )
                  ],
                  onChanged: (value) {
                    print(value);
                    setState(() {
                      code = value;
                    });
                  },
                ),
    
    opened by pedroculque 2
  • Input erases one by one when mask is only letters(^a-zA-Z)

    Input erases one by one when mask is only letters(^a-zA-Z)

    if you type several characters and then press to erase it erases straight to a point, after that point it only erases one by one, this problem happened on devices with Android 10 and 12

    opened by ennesdes 0
  • [Feature Request] MaskTextInputFormatter for hh:mm

    [Feature Request] MaskTextInputFormatter for hh:mm

    Hi everyone, is it possible to format for hh:mm where de max value is 23:59 I've tried THIS final timeMaskFormatter = MaskTextInputFormatter( mask: 'hH:mM', filter: { 'h': RegExp(r'^[0-2]$'), 'H': RegExp(r'^[0-9]$'), 'm': RegExp(r'^[0-5]$'), 'M': RegExp(r'^0?[0-9]$') }, );

    not sure how to manage this,

    Thanks in advance

    opened by ManuelFEMartinho 0
  • Composing region changed by the framework. restarting the input method.

    Composing region changed by the framework. restarting the input method.

    I always used to use this package like this:

    image

    Recently I update my flutter from 1.22.6 to 2.5.3 and migrate to null safety.

    Now this annoying behavior happens to me using this formatter above:

    https://user-images.githubusercontent.com/31242886/143131001-e780c12b-c361-442d-b75b-a0a30a9ef874.mp4

    Every time I type a number the keyboard turns back to letters, and the console look like this:

    I/TextInputPlugin(16562): Composing region changed by the framework. Restarting the input method.
    W/IInputConnectionWrapper(16562): beginBatchEdit on inactive InputConnection
    W/IInputConnectionWrapper(16562): getTextBeforeCursor on inactive InputConnection
    W/IInputConnectionWrapper(16562): getTextAfterCursor on inactive InputConnection
    W/IInputConnectionWrapper(16562): getSelectedText on inactive InputConnection
    W/IInputConnectionWrapper(16562): endBatchEdit on inactive InputConnection
    

    Can anybody help me?

    opened by edsonboldrini 6
  • mask for IP v4 Address

    mask for IP v4 Address

    Hi, I would like to mask IP Address in TextFormField. The following code is partially written and does not work. Please advice.

    new MaskTextInputFormatter(mask: '#.#.#.#',
        filter: {
          '#': new RegExp(r'^([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$')
        }); 
    ...
    For each value, the number should be between 0-255.
    opened by insinfo 1
Owner
Sergey
Sergey
Flutter Plugin - Simple character blocked input that usually used for redeem/validation input.

Block Input Simple character blocked input that usually used for redeem code or validation code input. Gallery Example Full example import 'package:bl

Enkh-Amar 7 Nov 2, 2022
Verify code input. You can create a verify code input.

flutter_verification_code_input A Flutter package that help you create a verification input. Installing flutter_verification_code_input: git:

Tiny Express 49 Dec 7, 2022
Verify code input. You can create a verify code input.

flutter_verification_code_input A Flutter package that help you create a verification input. Installing flutter_verification_code_input: git:

Tiny Express 49 Dec 7, 2022
🇮🇪 A generic programming language interpreter, linter, formatter, and all that jazz, written in Dart.

Irishman ???? A generic programming language interpreter, linter, formatter, and all that jazz, written in Dart. Installation To install this package

Fairfield Programming Association 2 Oct 8, 2022
Text analyzer that extracts tokens from text for use in full-text search queries and indexes.

Tokenize text, compute document readbility and compare terms in Natural Language Processing. THIS PACKAGE IS PRE-RELEASE, and SUBJECT TO DAILY BREAKIN

GM Consult Pty Ltd 5 Dec 12, 2022
🔥🚀 Flutter package to create Pin code input text field with every pixel customization possibility 🎨 with beautiful animations

Flutter PinPut From Tornike ?? ?? Flutter package to create Pin code input (OTP) text field with every pixel customization possibility ?? and beautifu

Tornike 451 Jan 2, 2023
An Instagram like text editor Flutter widget that helps you to change your text style.

TextEditor An instagram like text editor widget for flutter Show some ❤️ and star the repo to support the project Features Edit TextStyle object font

Mehdi Zarepour 68 Dec 16, 2022
Grad text package - A Flutter Widget to draw gradients into text

grad_text A Flutter Widget to draw gradients into text.(Null safe) Demo Install

Karthik Sunil K 3 Jan 31, 2022
Detectable text field - Flutter Text widgets with detection features

detectable_text_field Text widgets with detection features. You can detect hasht

null 0 Feb 2, 2022
A text field that displays text on different languages based on your selection.

translatable_text_field A text field that displays text on different languages based on your selection. Its basic idea is that you place this fields i

null 0 Mar 13, 2022
Introduction to flutter app final input

TASK CREATOR Introduction to Flutter URSB Webinar Topics What is flutter Why Flutter ? Flutter architecture Advantage and Disadvantage Widgets State A

Nehry Dedoro 2 Aug 28, 2022
MoneyTextFormField is one of the flutter widget packages that can be used to input values in the form of currencies, by displaying the output format in realtime.

MoneyTextFormField MoneyTextFormField is one of the flutter widget packages that can be used to input values in the form of currencies, by displaying

Fadhly Permata 11 Jan 1, 2023
Input fields for Flutter standalone or within a form

Flutter Input Widgets - Standalone or within a Form → flutter_input This package provides input widgets (fields) to manipulate data. The data to manip

null 7 Mar 14, 2021
A Flutter package that help you create a verification input.

flutter_verification_code A Flutter package that help you create a verification input. Based on https://github.com/tiny-express/flutter_verification_c

Alex Awaik 21 Dec 15, 2022
Flutter package for Android and iOS allow you to show a wide range of hyperlinks either in the input field or in an article view

Tagtly package help you to detect a lot of hyperlink text such as.. email, url, social media tags, hashtag and more either when user type in text field or when appear a text read only.

Mohamed Nasr 4 Jul 25, 2022
This is an auction application just like eBay. Using firebase as the backend for signup & sign-in functionality. In addition to that, it's a two pages application with user bid in input and count down view.

Nilam This is an auction application just like eBay. Using firebase as the backend for signup & sign-in functionality. In addition to that, it's a two

Md. Siam 5 Nov 9, 2022
A Dart widget for entering international telephone numbers with dropdown searching input countries

Dart Tel Input A Dart widget for entering international telephone numbers with dropdown searching input countries Getting Started Add the following li

աɨռɢӄաօռɢ 8 Oct 29, 2020
TheMathU Similarity Index App will accept a mathematical problem as user input and return a list of similar problems that have memorandums.

Technologies MathU Similarity Index - Segmentation Cult The MathU Similarity Index App accepts a mathematical problem as user input and returns a list

COS 301 - 2022 7 Nov 2, 2022
Flutter plugin for selecting images from the Android and iOS image library, taking new pictures with the camera, and edit them before using such as rotation, cropping, adding sticker/text/filters.

advance_image_picker Flutter plugin for selecting multiple images from the Android and iOS image library, taking new pictures with the camera, and edi

Weta Vietnam 91 Dec 19, 2022