Restrict leading zero in TextFormField in Flutter - flutter

Currently, I'm looking at a TextFormField restriction.
My requirement is
Allow single 0 in TextFormField
If it is 099, I want to remove the leading 0. So, it's 99
Do not allow symbols or special characters like "?" or "."
I have tried the below code, but it's still allowed to input "?" or "."
inputFormatters: [
new FilteringTextInputFormatter.allow(new RegExp("[0-9.]")),
new FilteringTextInputFormatter.deny(RegExp(r'^0+(?=.)')),
],
I am seeking your help on this.
Thanks in advance!

you can create a text controller at first :
TextEditingController textEditingController = TextEditingController();
then you can apply this text field :
TextFormField(
keyboardType: TextInputType.number,
controller: textEditingController,
onChanged: (val){
if(val.characters.characterAt(0) == Characters("0") && val.length > 1){
// we need to remove the first char
textEditingController.text = val.substring(1);
// we need to move the cursor
textEditingController.selection = TextSelection.collapsed(offset: textEditingController.text.length);
}
},
)
like this you will be able to enter a single zero but you will not be able write 099 it will be converted automatically to 99 .

Try below code:
TextFormField(
keyboardType: TextInputType.phone,
inputFormatters: [
FilteringTextInputFormatter.deny(
RegExp(r'^0+'),
),
],
),

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.

how to display no. of character user can type and how many characters user had typed in TextFormField Flutter

How can we display the count of input characters entered by the user and how many characters user can type in that TEXTFORMFIELD in Flutter? Like this
image credits : blog link
You can add maxLength property (it will show the writtenCharacters/totalLimit)
TextFormField(
maxLength: 45,
)
Or you can also have alternative (it will not show the writtenCharacters/totalLimit), but for this you need to import
import 'package:flutter/services.dart';
TextFormField(
inputFormatters: [
LengthLimitingTextInputFormatter(45),
],
)
You can still use a TextField and achieve what a TextFormField do by saving the input of the TextField to a variable on text changed
TextField(
maxLines: 3,
maxLength: 30,
onChanged: (value) {
_content = value;
},
),
and send _content on your form submit
With a TextFormField you can have the number of input character by passing an
TextEditingController to the TextFormField
final _myTextEditingController = TextEditingController();
TextFormField(
controller: _myTextEditingController,
maxLength: 30
)
and show the number of character with
_myTextEditingController.text.length

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+'))
]

How to ignore newlines in TextField?

Simple question that I'm not finding an answer to--I have a TextField that's multi-line but I don't want to allow newlines in the text. E.g., if the user is typing and hits [Enter], I don't want a newline to register in the TextField. How do I do that?
I tried catching it in the onChanged event, but got weird rendering results:
onChanged: (value) {
if (value.endsWith('\n')) {
_textController.text = value.trim();
}
},
You should try using BlacklistingTextInputFormatter in inputFormatters.
inputFormatters: [
FilteringTextInputFormatter.deny(new RegExp(r"\n"))
],
What if you use following parameters:
TextField(keyboardType: TextInputType.text, maxLines: 3,);