Dart flutter TextField to accept only digit and decimal - flutter

I have TextFormField and i want to allow only number and 1 "." and also only 2 digit after decimal.
I have set below things :
keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.allow((RegExp("[0-9.0-9]"))) ],
But this one allows me to enter multiple "." and unlimited after decimal.
I want to allow digits and only 1 "." and only 2 digits after "."
How can i do that?

I got it. It should be
keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r'^(\d+)?\.?\d{0,2}')), FilteringTextInputFormatter.allow(RegExp(r'^\d+\.?\d*')) ],

You can use the
onChanged : (val) {
// your logic here
}
eg: -
TextFormField(
controller: numberController,
decoration: const InputDecoration(
label: Text(
'Enter Number'
),
),
keyboardType: TextInputType.number,
onChanged: (val){
if(val.indexOf('.') != val.lastIndexOf('.')){
numberController.text = val.substring(0, val.length -1);
showDialog(context: context, builder: (ctx) => AlertDialog(
title: const Text('Please enter valid number'),
actions: [
IconButton(
onPressed: (){
Navigator.of(context).pop();
},
icon: const Icon(Icons.close))
],
));
}
},
),
to check the values dynamically. You can use, control and change your values and fields there.
or you can use the simplest solution from Alex

Related

How to force the user to enter an specific number in Flutter?

By using TextEditingController in Flutter, I'm trying to force the user to enter a number that starts with zero and then the number 4 or 8, then enter whatever he wants. Like this:
04****** or 08******
What should I do?
My code:
TextFormField(
maxLength: 10,
controller: _inputdat,
inputFormatters: [ FilteringTextInputFormatter.digitsOnly,],
keyboardType: TextInputType.number),
ElevatedButton(
......
onPressed: () async {
if (_inputdat.text.length < 10
|| !RegExp(r'^[0][8/4/2]{1}[0-9]{8}$').hasMatch(value))
{
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
backgroundColor: Color(0xff446d74),
content: Text(
"Error",
)));
What's wrong with my code? I got the error: Undefined name 'value'.
You can use https://pub.dev/packages/mask_text_input_formatter and do something like this:
var maskFormatter = new MaskTextInputFormatter(
mask: '0*########',
filter: { "*": RegExp(r'[48]'), "#": RegExp(r'[0-9]') },
type: MaskAutoCompletionType.lazy
);
and then pass maskFormatter to your text filed
TextField(inputFormatters: [maskFormatter])
Use this regex in the TextFormFiled validator r'^0[48][0-9]{7}$'
If you want to specify a specific number in total you can specify it in this part [0-9]{7} instead of seven you can choose different number.
This regex has in total of 9 numbers:
start with Zero 0
Second choose one 4 or 8 [48]
Third choose any 7 number [0-9]{7}
The validator should look something like this:
validator: (value) {
if (value!.isEmpty || !RegExp(r'^0[48][0-9]{7}$').hasMatch(value)) {
return "error message";
} else {
return null;
}
},
initialize a form key like below:
final formKey = GlobalKey<FormState>();
Full code:
Form(
autovalidateMode: AutovalidateMode.onUserInteraction,
key: formKey,
child: Column(
children: [
TextFormField(
validator: (value) {
if (value!.isEmpty || !RegExp(r'^0[48][0-9]{7}$').hasMatch(value)) {
return "error message";
} else {
return null;
}
},
decoration: const InputDecoration(
errorMaxLines: 2, // specify how many error lines you want
border: OutlineInputBorder(),
labelText: 'number',
),
maxLength: 10,
controller: _inputdat,
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
keyboardType: TextInputType.number),
ElevatedButton(
onPressed: () {
if (formKey.currentState!.validate()) {
// do something like a function or toast message etc...
}
},
child: const Text('Confirm'),
),
],
),
),

I wanna limit value of a quantity that user put on the text field (Flutter)

I want a user can input no more than 100 in my textfield.
If a user put more than 100 --let's say 123--, the text will show 100 instead of 123.
here is my code
TextField(
controller: qtyController,
keyboardType: TextInputType.number,
onTap: () => qtyController.text = '',
inputFormatters: [FilteringTextInputFormatter. digitsOnly,
LengthLimitingTextInputFormatter(3),
],
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white),
)
You can use the onChanged callback to listen to the changes
TextField(
controller: qtyController,
keyboardType: TextInputType.number,
onTap: () => qtyController.text = '',
onChanged: (val){
if (val.isNotEmpty) {
if(int.parse(val)>=100) {
qtyController.text = "100";
}
}
},
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(3),
],
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white),
)
The simplest approach is to supply an onChanged() callback to a TextField or a TextFormField. Whenever the text changes, the callback is invoked.
A more powerful, but more elaborate approach, is to supply a TextEditingController as the controller property of the TextField or a TextFormField.
Details on here:https://docs.flutter.dev/cookbook/forms/text-field-changes
You can use the maxLength property to set the maximum characters allowed in the TextField. Read more about it here.

How to prefix two decimal number in textfield

I'm new with flutter and wondering is it possible to prefix the number with decimal in textfield. The prefix number is 0.00 and should not delete it.
<blockquote class="imgur-embed-pub" lang="en" data-id="VnFQQlo">View post on imgur.com</blockquote><script async src="//s.imgur.com/min/embed.js" charset="utf-8"></script>
So far i have tried something like limited two decimal entry.
CupertinoFormRow(
child: CupertinoTextFormFieldRow(
controller: controller.price,
onChanged: (value) {
controller.calTotal(controller.qty.text, value);
},
placeholder: "Enter item price",
inputFormatters: [
FilteringTextInputFormatter.allow(
RegExp(r'^\d+\.?\d{0,2}')),
],
),
prefix: Text('0.00'),
),
Use currency_text_input_formatter
CupertinoFormRow(
child: CupertinoTextFormFieldRow(
controller: controller.price,
onChanged: (value) {
controller.calTotal(controller.qty.text, value);
},
placeholder: "Enter item price",
inputFormatters: [
CurrencyTextInputFormatter(decimalDigits: 2),
],
),
),

How do I use the credit card date format mm/yy in FLUTTER

child: new TextFormField(
maxLength:5,
controller:
TextEditingController(text: donation.date),
onChanged: (value) {
donation.date = value;
},
decoration: InputDecoration(
suffixText: '',
suffixStyle: TextStyle(
color: Color(0xffde0486),
),
labelText: 'Expiry Date',
border: OutlineInputBorder(),
),
keyboardType: TextInputType.number,
textInputAction: TextInputAction.done,
style: TextStyle(color: Colors.white),
autofocus: true,
),
I have this piece of code for a credit card that I am implementing in Flutter. I want to put the mm/yy format on the textfield. When the user has entered the month, the text field should automatically show the '/'. How do I do this?
You can achieve your result using the onChange method. You can check the length of the input and insert a '/' into the text if it is 2 i.e. dd
You need to store the controller in a seperate variable, because we want to use it later for inserting '/':
var _controller = new TextEditingController(text: donation.date);
Add this _controller and onChange callback to your TextFormField:
TextFormField(
controller: _controller, //<-- Add controller here
onChanged: (value) {
if(value.length == 2) _controller.text += "/"; //<-- Automatically show a '/' after dd
donation.date = value;
},
...
),
Yo can try this package flutter_multi_formatter to format the Expiration Date field as well as the credit card number field.
Update !
I just found a package: flutter_masked_text2 that can help you solve the problem!
var controller = new MaskedTextController(mask: '00/00');

Insert prefix text into database in flutter

can I insert prefix text into the database? prefix text like this:
I think prefix text (+62) entered the database when it was submitted but no ... is there another way to have +62 auto in TextFormField and can it enter the database ??
and this is my code `
TextFormField(
controller: controllerPhone,
decoration: InputDecoration(
labelText: "Phone",
icon: Icon(Icons.phone),
prefixText: '+62',
),
validator: validatePhoneNumber,
onSaved: (String value) {
phone = value;
}, ),
`
Make the prefix a variable and concatenate it in your onSaved():
String _prefix = '+62'; // somewhere in your code
TextFormField(
controller: controllerPhone,
decoration: InputDecoration(
labelText: "Phone",
icon: Icon(Icons.phone),
prefixText: _prefix,
),
validator: validatePhoneNumber,
onSaved: (String value) {
phone = '$_prefix $value';
},
Let me know how this works out for you.