Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 472
Renik Shiroya Avatar asked Oct 12 '25 17:10

Renik Shiroya


1 Answers

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]"),
    ),
  ],
),

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!