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

Mohammed Ali
  • 1,117
  • 1
  • 16
  • 31

4 Answers4

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+')),
                  ],
...
gsm
  • 2,348
  • 17
  • 16
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+'), '');,
),
savke
  • 268
  • 1
  • 3
  • 11
1
      String phone = '000345';
      String editedPhone = phone.replaceFirst(RegExp(r'^0+'), "");
      print(phone);
      print(editedPhone);

Will print:

000345
345
Robert Sandberg
  • 6,832
  • 2
  • 12
  • 30
0
inputFormatters: [
            FilteringTextInputFormatter.digitsOnly,
            FilteringTextInputFormatter.deny(RegExp('^0+'))
          ]
Linar
  • 903
  • 6
  • 10