Jimmy Vailer
Jimmy Vailer

Reputation: 493

Flutter: Adding a hyphen and brackets to a user's phone number entered in a textfield

I am trying to rearrange a user's entered phone number with brackets around the area code and a hyphen. For example, the user would enter 9991234567 and it would be rearranged to (999) 123-4567 inside the textfield.

I'm using a RegExp to separate the user's entry into the area code, and the 2 parts of the phone number. I am attempting to use a TextEditingController to edit the text field with brackets and a hyphen when the Save button is pressed but it does not seem to work.

_saveButtonPressed() async {
    RegExp phone = RegExp(r'(\d{3})(\d{3})(\d{4})');
    var matches = phone.allMatches(UserProfile.instance.phone);
    var match = matches.elementAt(0);
    setState(() {
      phoneController.text = '(${match.group(1)}) ${match.group(2)}-${match.group(3)}';
    });
  }

This is the code for the phone number textfield.

  _makeRowForAttribute(
            imageAsset: "assets/images/phone.png",
            title: "PHONE NUMBER",
            keyboardType: TextInputType.phone,
            placeholder: "6131110123",
            charLimit: 10,
            initialValue: UserProfile.instance.phone,
            controller: phoneController,
            onSave: (phone) {
              UserProfile.instance.phone = phone.toString();
            },
          ),

Upvotes: 1

Views: 3844

Answers (2)

Nasir Jafarzadeh
Nasir Jafarzadeh

Reputation: 6453

You can simply use flutter_masked_text package

It's just simple as following

import 'package:flutter_masked_text/flutter_masked_text.dart';

class MobileNumberTextField extends StatefulWidget {
  createState() => MobileNumberTextFieldState();
}

class MobileNumberTextFieldState extends State<MobileNumberTextField> {

  final controller =MaskedTextController(mask: "(000) 000-0000");

  @override
  Widget build(BuildContext context) {

    return TextField(
      controller: controller,
      keyboardType: TextInputType.number,
      autofocus: true,
    );
  }
}

Hope it will be helpful

Upvotes: 1

Tor-Martin Holen
Tor-Martin Holen

Reputation: 1639

I think this should do the trick.

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class FormattedPhoneNumber extends StatefulWidget {
  @override
  _FormattedPhoneNumberState createState() => _FormattedPhoneNumberState();
}

class _FormattedPhoneNumberState extends State<FormattedPhoneNumber> {
  String text = "";

  convert(TextEditingValue oldValue, TextEditingValue newValue) {
    print("OldValue: ${oldValue.text}, NewValue: ${newValue.text}");
    String newText = newValue.text;

    if (newText.length == 10) {
      // The below code gives a range error if not 10.
      RegExp phone = RegExp(r'(\d{3})(\d{3})(\d{4})');
      var matches = phone.allMatches(newValue.text);
      var match = matches.elementAt(0);
      newText = '(${match.group(1)}) ${match.group(2)}-${match.group(3)}';
    }

    // TODO limit text to the length of a formatted phone number?

    setState(() {
      text = newText;
    });

    return TextEditingValue(
        text: newText,
        selection: TextSelection(
            baseOffset: newValue.text.length,
            extentOffset: newValue.text.length));
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: TextField(
            inputFormatters: [
              TextInputFormatter.withFunction(
                  (oldValue, newValue) => convert(oldValue, newValue)),
            ],
            keyboardType: TextInputType.phone,
            decoration: InputDecoration(
                border: OutlineInputBorder(),
                hintText: "input",
                labelText: "Converts to phone number format"),

            // Fixes a problem with text-caret only being at the start of the textfield.
            controller: TextEditingController.fromValue(new TextEditingValue(
                text: text,
                selection: new TextSelection.collapsed(offset: text.length))),
          ),
        ),
      ],
    );
  }
}

Hope it helps :-)

Upvotes: 0

Related Questions