remove the first zeros of phone input TextFormField of type numbers flutter

4.2k views Asked by At

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

4

There are 4 answers

0
savke On BEST ANSWER

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+'), '');,
),
0
Robert Sandberg On
      String phone = '000345';
      String editedPhone = phone.replaceFirst(RegExp(r'^0+'), "");
      print(phone);
      print(editedPhone);

Will print:

000345
345
1
gsm On

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+')),
                  ],
...
0
Linar On
inputFormatters: [
            FilteringTextInputFormatter.digitsOnly,
            FilteringTextInputFormatter.deny(RegExp('^0+'))
          ]