Renik Shiroya
Renik Shiroya

Reputation: 379

How to accept only numbers in TextFormFields?

I want to accept only numbers in TextFormFields. I have designed a TextFormField for accepting phone numbers. I have changed the keyboard type.

keyboardType: TextInputType.phone,

But, it can also accept special symbols or can paste other inputs also. Keyboard screenshots

Upvotes: 4

Views: 9664

Answers (5)

Ravindra S. Patil
Ravindra S. Patil

Reputation: 14895

Try below code, refer FilteringTextInputFormatter

import below library

import 'package:flutter/services.dart';

Your Widget: 1st Way

    TextFormField(
       keyboardType: TextInputType.number,
       inputFormatters: [FilteringTextInputFormatter.digitsOnly],
    ),

Your Widget: 2nd Way (Using RegExp )

TextFormField(
  keyboardType: TextInputType.number,
  inputFormatters: [
    FilteringTextInputFormatter.allow(
      RegExp("[0-9]"),
    ),
  ],
),

Upvotes: 19

Abin vs
Abin vs

Reputation: 143

Simply, This could Work:

keyboardType: TextInputType.number,

Upvotes: 0

Shailendra Rajput
Shailendra Rajput

Reputation: 2982

You can use FilteringTextInputFormatter.

 TextField(
            keyboardType: TextInputType.number,
            inputFormatters: <TextInputFormatter>[
              FilteringTextInputFormatter.digitsOnly
            ], // Only numbers can be entered
          ),

Upvotes: 2

Arbiter Chil
Arbiter Chil

Reputation: 1285

Try used input formatter

import 'package:flutter/src/services/text_formatter.dart';

TextFormField(
      keyboardType: TextInputType.phone,
      inputFormatters:
      [
        FilteringTextInputFormatter.digitsOnly
      ]
    )

Upvotes: 2

K_Chandio
K_Chandio

Reputation: 807

In Your TextFormField add:

inputFormatters: [
   FilteringTextInputFormatter.allow(
        RegExp("[0-9]")),
   ],

You can also modify RegExp for supporting any kind of input characters.

Upvotes: 1

Related Questions