remove the first zeros of phone input TextFormField of type numbers flutter
Asked Answered
S

4

6

how can i remove the first zeros of phone number like 00963 and 031 and so on in flutter inside TextFormField ?
here is my code of theTextFormField :

TextFormField(
             keyboardType: TextInputType.phone,
              onSaved: (input) => _con.user.phone = input,
             ),

my question is not to prevent the user enter the zeros but to get it with phone number without first zeros if the user entered it or not

Setscrew answered 15/10, 2020 at 8:33 Comment(0)
M
3

If you want to remove all first zeros from phone number just use this regex expression:

 new RegExp(r'^0+')

^ - match the beginning of a line

0+ - match the zero digit character one or more times

Final code for your TextFormField:

TextFormField(
  keyboardType: TextInputType.phone,
  onSaved: (input) => _con.user.phone = input.replaceFirst(new RegExp(r'^0+'), '');,
),
Mettle answered 15/10, 2020 at 8:56 Comment(0)
G
7

The above answer is correct but if you using **TextFormField** following example will be worth,

TextFormField(
   controller: familyMemberPhoneController,
   inputFormatters: [
     FilteringTextInputFormatter.allow(RegExp('[0-9]')),
     //To remove first '0'
     FilteringTextInputFormatter.deny(RegExp(r'^0+')),
     //To remove first '94' or your country code
     FilteringTextInputFormatter.deny(RegExp(r'^94+')),
                  ],
...
Guild answered 30/9, 2021 at 10:1 Comment(1)
Correct approach. Works perfectly.Text
M
3

If you want to remove all first zeros from phone number just use this regex expression:

 new RegExp(r'^0+')

^ - match the beginning of a line

0+ - match the zero digit character one or more times

Final code for your TextFormField:

TextFormField(
  keyboardType: TextInputType.phone,
  onSaved: (input) => _con.user.phone = input.replaceFirst(new RegExp(r'^0+'), '');,
),
Mettle answered 15/10, 2020 at 8:56 Comment(0)
D
1
      String phone = '000345';
      String editedPhone = phone.replaceFirst(RegExp(r'^0+'), "");
      print(phone);
      print(editedPhone);

Will print:

000345
345
Dew answered 15/10, 2020 at 8:54 Comment(0)
T
0
inputFormatters: [
            FilteringTextInputFormatter.digitsOnly,
            FilteringTextInputFormatter.deny(RegExp('^0+'))
          ]
Trireme answered 28/9, 2022 at 11:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.