TextField that only takes decimal number - flutter

I'm trying to use the inputFormatters attribute to restrict input to a decimal number. The way to do that seems to be a regex string, however, it doesn't allow any input for some reason. If I just have a dot as regular expression, it works fine, but there's something about the complexity of the string that breaks functionality. Here's my code:
TextField(
keyboardType: TextInputType.number,
maxLines: 1,
maxLength: 8,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(RegExp("/^(0|[1-9]\\d*)(\\.\\d+)?\$/"))],
onChanged: (value) => setState(() {
valoare = value;
})
),

The problem is the inputFormatters: are apparently running on each keystroke, even on partial input (input so far).
So to enter 123.45 (which is valid), you must go through a step that where the value is "123.", but that's invalid, and now you're toast. Move your validation instead to the "validate:" method, which is called only when the input is complete.

you can use options with keyboard type
like
keyboardType: TextInputType.numberWithOptions(decimal: true,signed: false),

Related

Flutter: Is it possible to show a Message to User when TextFormField inputFormatter trims the text?

While the inputFormatters is realy well explained here and works like a charm I want to let the user know about what happened to his input.
A simple snackBar or other dialog should be shown that prompts the user: "Your code has been trimmed because of unallowed signs. You are only allowed to enter numbers and letters!"
my example code shows the limitation to numbers and letters:
TextFormField( inputFormatters: <TextInputFormatter>[ FilteringTextInputFormatter.allow( RegExp("[0-9a-zA-Z]"), ), ],
If the user paste a string that contains other signs they will be deleted automaticly but the user might not see that so I want to show a warning to him.
I appriciate all help.
Thanks for your answeres but I solved it on my own as follows:
The inputFormatter blocks all unallowed signs and won't show them in onChanged value of the textController but the onChanged function is triggered and stays even. So I added the following code to the onChanged: function:
onChanged: (val) {
if (count == val.length) {
showSnackBar(
context,
'You entered an unallowed sign!',
icon: Icons.warning_outlined, // this is from my own class showSnackBar which shows a Row with an optional Icon
);
}
count = val.length;
Everytime the user types an unallowed sign this warning pops up because the textcontroller changed but the value of it stays the same.
If there are parts I can do better please comment and I'll correct them.
The complete Code of the TextFormField including the inputFormatters:
First i created a variabel int count = 0;
TextFormField(
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(
RegExp("[0-9a-zA-Z]"),
),
],
obscureText: false,
controller: _controller,
decoration: InputDecoration(
labelText:
'title',
),
onChanged: (val) {
if (count == val.length) {
showSnackBar(
context,
'Unallowd sign typed in!',
icon: Icons.warning_outlined,
);
}
model.textChanged(val);
count = val.length;
},
),
Thanks

How to format the numbers as we type and check validation in TextField in flutter?

I have a text field and currently I am enforcing validation using RegExp as follows:
TextField(
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.allow(
RegExp(r'(^\d*\.?\d*)'),
),
LengthLimitingTextInputFormatter(12),
],
onChanged: (value) {
setState(() {
if (value.isNotEmpty) {
initialValue = double.parse(value);
} else if (value.isEmpty) {
initialValue = 0;
}
});
},
decoration: InputDecoration(
border: OutlineInputBorder(),
),
),
Now I want the number to be formatted with commas (Eg: 1,23,45,678.901) as the user types the number in the TextField. How can I implement this?
I went through this TextInputFormatter-class and EditableText on the flutter docs but did not understand much. So is there a simpler way or should we using EditableText?
Also, in the RegExp I want it to accept commas between numbers but obviously before the decimal as validation.
The easiest way is to look at existing packages. mask_text_input_formatter does exactly what you are describing.

Flutter: detect if a string can be converted to double

I can do something like this:
double.parse(myString)
That's fine when I have "1.1" but if I have "1.1.1" it fails with Invalid double. Could I detect this somehow in advance?
I'd need this for input validations
Working with
double.tryParse(myString)
As written above, use double.tryParse() or wrap double.parse() with try catch
An alternative, if you need to do input validation could be filter away "bad" input already when the user inputs the number.
You could change keyboard type and use input formatters on a TextField / TextFormFiel
TextField(
decoration: new InputDecoration(labelText: "Enter your number"),
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter> [
FilteringTextInputFormatter.digitsOnly
], // Only numbers can be entered
),
You could write something like this
if(!myString.contains(<someregex>)) {
double.parse(myString);
}
Where the regex is validating that the string is a valid double, the value of doing this over using tryParse is that you can include your business rule validation alongside your datatype validation.

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

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
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+')),
],
...
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+'), '');,
),
String phone = '000345';
String editedPhone = phone.replaceFirst(RegExp(r'^0+'), "");
print(phone);
print(editedPhone);
Will print:
000345
345
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
FilteringTextInputFormatter.deny(RegExp('^0+'))
]

Flutter : Keyboard without decimal point

I need a numberInputKeyboard which only has numbers (without decimal symbol). I have tried with keyboardType: TextInputType.numberWithOptions(decimal: false) but still this dosen't help me
One answer recommends using a BlacklistingTextInputFormatter which certainly works in your case with English locale. This however might not work with other locales which use a , instead of a . as decimal seperator.
So I'd recommend using a WhitelistingTextInputFormatter:
import "package:flutter/services.dart";
TextFormField(
keyboardType: TextInputType.number,
inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
)
This will only allows the digits [0-9].
UPDATE:
The WhitelistingTextInputFormatter as been renamed! The following is the up-to date version and no longer deprecated by FilteringTextInputFormatter.allow and provides a shortcut for the digits as well:
import "package:flutter/services.dart";
TextFormField(
keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
)
BlacklistingTextInputFormatter and WhitelistingTextInputFormatter are deprecated. If you want to admit digits only, you could use:
FilteringTextInputFormatter.digitsOnly
If you want to admit numbers with decimal point:
FilteringTextInputFormatter.allow(RegExp(r'^(\d+)?\.?\d{0,2}')
First Approach :-
As per this stackoverflow answer you must have to create your custom keyboard for it.
Android - is it possible to hide certain characters from the soft keyboard?
Second Approach :-
You can do black list that stuff with RegExp, in this case you can't input dot(.).
For more you can refer this : https://api.flutter.dev/flutter/services/TextInputFormatter-class.html
body: Center(
child: TextFormField(
decoration: InputDecoration(
labelText: "Title",
suffixIcon: GestureDetector(
onTap: () {
setState(() {
});
},
child: Icon(Icons.clear),
)),
inputFormatters: [
FilteringTextInputFormatter.deny(RegExp("[.]")),
],
)));
To aport this thread i did this, helped with the link provided by Amit Prajapati, its a but more manual but in my case worked perfectly
inputFormatters: [
TextInputFormatter.withFunction((oldValue, newValue) {
if (textInputType.decimal == true) {
return newValue.copyWith(
text: newValue.text.replaceAll(RegExp(r"\,"), "."),
);
}
return newValue;
}),
],
EDIT: textInputType is a variable for a custom TextField