Home > Blockchain >  How to Restrict special characters like except numbers 0 to 9 in onchanged for textfield
How to Restrict special characters like except numbers 0 to 9 in onchanged for textfield

Time:07-29

The following is my onChanged method for phone number textfield. I want only numbers to be accepted. but it is accepted all characters except alphabets a-z and A-Z

 onChanged: (value) {
                                  if (value.contains(RegExp(r'[a-z,A-Z]')) ||
                                      value.isEmpty) {
                                    setState(() {
                                      _isPhone = false;
                                    });

CodePudding user response:

make use of InputKeyboardtype

Only allow number input in flutter text field Flutter

 TextFormField(
              initialValue: _tip.toString(),
              inputFormatters: [FilteringTextInputFormatter.digitsOnly],
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                  prefix: Text('\$'),
                  labelText: 'Enter Custom Tip Amount ',
                  hintStyle: TextStyle(fontWeight: FontWeight.w600)),
              onChanged: (val) => setState(() => _tip = int.tryParse(val) ?? 0),
            ),

CodePudding user response:

Use input formatter

inputFormatters: [FilteringTextInputFormatter.digitsOnly],

Add this to your textfield and/or if you wish to check the number in on changed then you can try this

onChanged : (value) {
  
  final valueNum = num.tryParse(value);
  if(valueNum == null) {
    //Not phone
     return;
  }
  //Is phone. Setstate here as phone true
}
  • Related